2

我将这个 PHP 函数用于 SEO 网址。它适用于拉丁词,但我的网址是西里尔字母。此正则表达式 -/[^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;
}
4

2 回答 2

2

您需要为西里尔字母使用 Unicode 脚本,幸运的是 PHP 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-16T16:00:21.723 回答
1

要了解有关Unicode 正则表达式的更多信息,请参阅这篇文章

\p{L}\p{Letter}匹配来自任何语言的任何类型的字母。

要仅匹配西里尔字符,请使用\p{Cyrillic}

由于西里尔字符不是标准的 ASCII 字符,您必须使用u标志/修饰符,因此正则表达式将根据需要识别 Unicode 字符。

当您使用 unicode 字符时,请务必使用mb_strtolower而不是。strtolower

因为您将所有字符都转换为小写,所以您不必使用i正则表达式标志/修饰符。


以下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}匹配所有非补充西里尔字符

于 2018-04-16T19:41:14.863 回答