// 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, being special, is escaped with \
$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
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
3 回答
十分简单:
Usage:
将输出:
abcdef-g
Edit:
更新
下面的解决方案有一个“SEO友好”版本:
上述函数的基本原理(我发现效率低下 - 下面的一个更好)是一个不应该命名的服务显然对URL进行了拼写检查和关键字识别 .
在客户的偏执狂失去了很长一段时间之后,我发现他们毕竟不是想象 - 他们的SEO专家[我绝对不是一个]报告说,比如"Viaggi Economy Perù"转换为
viaggi-economy-peru
"behaved better"而不是viaggi-economy-per
(之前的"cleaning"已删除UTF8字符; Bogotà 成为 bogot , Medellìn 成为 medelln 等等) .还有一些常见的拼写错误似乎影响了结果,唯一对我有意义的解释是我们的URL被解包,单词被挑出来,用来驱动上帝知道什么是排名算法 . 这些算法显然已经用UTF8清理过的字符串,因此“Perù”变成了“秘鲁”而不是“Per” . “Per”没有匹配,有点把它放在脖子上 .
为了保持UTF8字符并替换一些拼写错误,下面更快的函数变成了上面更准确的(?)函数 . 当然,
$dict
需要手工定制 .以前的答案
一个简单的方法:
请注意,您可能必须首先
urldecode()
这个URL,因为%20并且两者实际上都是空格 - 我的意思是,如果你有"Never%20gonna%20give%20you%20up",你希望它变成永不放弃,而不是Never20gonna20give20you20up . 你可能不需要它,但我想我会提到这种可能性 .完成的功能以及测试用例:
为了处理UTF-8,我使用
cleanString
实现here . 它可以简化并包含在函数内部以提高性能 .上面的函数也实现了转换为小写 - 但这是一种品味 . 这样做的代码已经被注释掉了 .
在这里,看看这个功能: