我正面临一个问题与url,我希望能够转换标题,可以包含任何东西,并有他们剥夺所有特殊字符,所以他们只有字母和数字,当然我想用连字符代替空格。
如何做到这一点?我听说过很多关于正则表达式(regex)的使用…
这应该是你想要的:
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9'-]/', '', $string); // Removes special chars.
}
用法:
echo clean('a|"bc!@£de^&$f g');
将输出:abcdef-g
编辑:
嘿,只是一个快速的问题,我怎样才能防止多个连字符相邻?把它们换成1?
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9'-]/', '', $string); // Removes special chars.
return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
改进的清理
下面的解决方案有一个"SEO友好";版本:
function hyphenize($string) {
$dict = array(
"I'm" => "I am",
"thier" => "their",
// Add your own replacements here
);
return strtolower(
preg_replace(
array( '#[''s-]+#', '#[^A-Za-z0-9. -]+#' ),
array( '-', '' ),
// the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
cleanString(
str_replace( // preg_replace can be used to support more complicated replacements
array_keys($dict),
array_values($dict),
urldecode($string)
)
)
)
);
}
function cleanString($text) {
$utf8 = array(
'/[áàâãªä]/u' => 'a',
'/[ÁÀÂÃÄ]/u' => 'A',
'/[ÍÌÎÏ]/u' => 'I',
'/[íìîï]/u' => 'i',
'/[éèêë]/u' => 'e',
'/[ÉÈÊË]/u' => 'E',
'/[óòôõºö]/u' => 'o',
'/[ÓÒÔÕÖ]/u' => 'O',
'/[úùûü]/u' => 'u',
'/[ÚÙÛÜ]/u' => 'U',
'/ç/' => 'c',
'/Ç/' => 'C',
'/ñ/' => 'n',
'/Ñ/' => 'N',
'/–/' => '-', // UTF-8 hyphen to "normal" hyphen
'/[’‘‹›‚]/u' => ' ', // Literally a single quote
'/[“”«»„]/u' => ' ', // Double quote
'/ /' => ' ', // nonbreaking space (equiv. to 0x160)
);
return preg_replace(array_keys($utf8), array_values($utf8), $text);
}
上述功能的基本原理(我发现方式效率低下-下面的一个更好)是一个不应该命名的服务显然在url上运行拼写检查和关键字识别。
在客户的偏执狂上浪费了很长时间后,我发现他们毕竟不是想象的事情-他们的SEO专家[我绝对不是其中之一]报告说,例如,转换"Viaggi经济Perù"对viaggi-economy-peru
"表现得更好";比viaggi-economy-per
(之前的"清洗";删除UTF8字符;波哥大成为 bogot , 麦德林成为 medelln 等等)。
还有一些常见的拼写错误似乎影响了结果,对我来说唯一合理的解释是我们的URL被拆包了,单词被挑出来,用来驱动天知道是什么排名算法。这些算法显然是用utf8清理过的字符串输入的,所以"Perù"成为"Peru"而不是"Per"。"Per"不匹配,有点像打在脖子上。
为了既保留UTF8字符又替换一些拼写错误,下面更快的函数变成了上面更准确的函数。当然,$dict
需要手工裁剪。
一个简单的方法:
// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped
$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);
// Replace sequences of spaces with hyphen
$str = preg_replace('/ */', '-', $str);
// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)
// You may also want to try this alternative:
$str = preg_replace('/''s+/', '-', $str);
// where 's+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything
请注意,你可能必须首先urldecode()
URL,因为%20和+实际上都是空格-我的意思是,如果你有"Never%20gonna%20give%20you%20up"你希望它变成"永不放弃",而不是"永不放弃",而不是"永不放弃"。你可能不需要它,但我想我应该提一下这种可能性。
所以完成的函数和测试用例:
function hyphenize($string) {
return
## strtolower(
preg_replace(
array('#[''s-]+#', '#[^A-Za-z0-9. -]+#'),
array('-', ''),
## cleanString(
urldecode($string)
## )
)
## )
;
}
print implode("'n", array_map(
function($s) {
return $s . ' becomes ' . hyphenize($s);
},
array(
'Never%20gonna%20give%20you%20up',
"I'm not the man I was",
"'Légeresse', dit sa majesté",
)));
Never%20gonna%20give%20you%20up becomes never-gonna-give-you-up
I'm not the man I was becomes im-not-the-man-I-was
'Légeresse', dit sa majesté becomes legeresse-dit-sa-majeste
为了处理UTF-8,我使用了在线找到的cleanString
实现(链接已经断开,但是在答案的开头有一个带有所有不太深奥的UTF8字符的剥离副本;它也很容易添加更多的字符,如果你需要)转换UTF8字符到正常字符,从而保留单词的"外观"。尽可能多。为了提高性能,它可以被简化并包装在这里的函数中。
上面的函数也实现了小写字母的转换——但这只是一个尝试。执行此操作的代码已被注释掉。
标题>这里,看看这个函数:
function seo_friendly_url($string){
$string = str_replace(array('['', '']'), '', $string);
$string = preg_replace('/'[.*']/U', '', $string);
$string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
$string = htmlentities($string, ENT_COMPAT, 'utf-8');
$string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '''1', $string );
$string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
return strtolower(trim($string, '-'));
}