I managed to replace special characters such as : ; / etc in my URL but now it has the spaces again. Here is my code:
我设法替换了特殊字符,例如:;我的URL中的/ etc,但现在又有了空格。这是我的代码:
<h3><a href="<?php echo (isset($row_getDisplay['post_id']) ? $row_getDisplay['post_id'] : ''); ?>_<?php echo str_replace(array(':', '\\', '/', '*'), ' ', urldecode($row_getDisplay['title'])); ?>.html" ><?php echo (isset($row_getDisplay['title']) ? $row_getDisplay['title'] : ''); ?></a></h3>
I want it to like it is remove special characters as well as replace spaces with dashes.
我希望它喜欢删除特殊字符以及用短划线替换空格。
2 个解决方案
#1
22
Try str_replace(' ', '-', $string);
尝试str_replace('',' - ',$ string);
#2
11
You can use preg_replace:
你可以使用preg_replace:
preg_replace('/[[:space:]]+/', '-', $subject);
This will replace all instances of space with a single '-' dash. So if you have a double, triple, etc space, then it will still give you one dash.
这将使用单个“ - ”破折号替换所有空间实例。因此,如果你有一个双倍,三倍等空间,那么它仍会给你一个破折号。
EDIT: this is a generec function I've used for the last year to make my URLs tidy
编辑:这是我去年用来使我的网址整洁的基因功能
function formatUrl($str, $sep='-')
{
$res = strtolower($str);
$res = preg_replace('/[^[:alnum:]]/', ' ', $res);
$res = preg_replace('/[[:space:]]+/', $sep, $res);
return trim($res, $sep);
}
It will convert all non-alphanumeric characters to space, then convert all space to dash, then trim any dashes on the end / beginning of the string. This will work better than having to list special characters in your str_replace
它会将所有非字母数字字符转换为空格,然后将所有空格转换为破折号,然后修剪字符串结尾/开头的任何破折号。这比在str_replace中列出特殊字符更有效
#1
22
Try str_replace(' ', '-', $string);
尝试str_replace('',' - ',$ string);
#2
11
You can use preg_replace:
你可以使用preg_replace:
preg_replace('/[[:space:]]+/', '-', $subject);
This will replace all instances of space with a single '-' dash. So if you have a double, triple, etc space, then it will still give you one dash.
这将使用单个“ - ”破折号替换所有空间实例。因此,如果你有一个双倍,三倍等空间,那么它仍会给你一个破折号。
EDIT: this is a generec function I've used for the last year to make my URLs tidy
编辑:这是我去年用来使我的网址整洁的基因功能
function formatUrl($str, $sep='-')
{
$res = strtolower($str);
$res = preg_replace('/[^[:alnum:]]/', ' ', $res);
$res = preg_replace('/[[:space:]]+/', $sep, $res);
return trim($res, $sep);
}
It will convert all non-alphanumeric characters to space, then convert all space to dash, then trim any dashes on the end / beginning of the string. This will work better than having to list special characters in your str_replace
它会将所有非字母数字字符转换为空格,然后将所有空格转换为破折号,然后修剪字符串结尾/开头的任何破折号。这比在str_replace中列出特殊字符更有效