如何将PHP变量从“我的公司和我的名字”转换为“我的公司-我的名字”?
我需要全部小写,删除所有特殊字符,并用破折号代替空格。
Answers:
此函数将创建一个SEO友好字符串
function seoUrl($string) {
//Lower case everything
$string = strtolower($string);
//Make alphanumeric (removes all other characters)
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
//Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
应该没事 :)
-符号的第一个和最后一个空格?
$string = trim($string);,这将解决您的问题。
替换特定字符:http : //se.php.net/manual/en/function.str-replace.php
例:
function replaceAll($text) {
$text = strtolower(htmlentities($text));
$text = str_replace(get_html_translation_table(), "-", $text);
$text = str_replace(" ", "-", $text);
$text = preg_replace("/[-]+/i", "-", $text);
return $text;
}