我使用这个PHP函数作为SEO。拉丁语很好,但我的urls在西里尔语上。这个regex - /[^a-z0-9_\s-]/不是使用西里尔字符,请帮助我使它与非拉丁字符工作。
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;
}发布于 2018-04-16 16:00:21
您需要为Cyrillic字母表使用Unicode脚本,幸运的是PCRE使用\p{Cyrillic}支持它。此外,您还必须设置u (unicode)标志来预测引擎行为。您还可能需要i标志来启用大小写不敏感(如A-Z )。
~[^\p{Cyrillic}a-z0-9_\s-]~ui你不需要双倍逃脱\s。
PHP代码:
preg_replace('~[^\p{Cyrillic}a-z0-9_\s-]+~ui', '', $string);发布于 2018-04-16 19:41:14
要了解关于Unicode正则表达式的更多信息,请参见这篇文章。
\p{L}或\p{Letter}与任何语言中的任何字母相匹配。
若要只匹配西里尔字符,请使用\p{Cyrillic}
因为西里尔字符不是标准的ASCII字符,所以您必须使用u标志/修饰符,因此regex将根据需要识别Unicode字符。
在使用unicode字符时,一定要使用mb_strtolower而不是strtolower。
因为您将所有字符转换为小写,所以不必使用i regex标志/修饰符。
下面的PHP代码应该适用于您:
function seoUrl($string) {
// Lower case everything
$string = mb_strtolower($string);
// Make alphanumeric (removes all other characters)
$string = preg_replace('/[^\p{Cyrillic}a-z0-9\s_-]+/u', '', $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;
}此外,请注意,\p{InCyrillic_Supplementary}匹配所有西里尔补充字符,\p{InCyrillic}匹配所有非补充西里尔字符。
https://stackoverflow.com/questions/49861408
复制相似问题