首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >移除所有特殊字符,但不移除非拉丁字符。

移除所有特殊字符,但不移除非拉丁字符。
EN

Stack Overflow用户
提问于 2018-04-16 15:49:44
回答 2查看 2.6K关注 0票数 2

我使用这个PHP函数作为SEO。拉丁语很好,但我的urls在西里尔语上。这个regex - /[^a-z0-9_\s-]/不是使用西里尔字符,请帮助我使它与非拉丁字符工作。

代码语言:javascript
复制
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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-16 16:00:21

您需要为Cyrillic字母表使用Unicode脚本,幸运的是PCRE使用\p{Cyrillic}支持它。此外,您还必须设置u (unicode)标志来预测引擎行为。您还可能需要i标志来启用大小写不敏感(如A-Z )。

代码语言:javascript
复制
~[^\p{Cyrillic}a-z0-9_\s-]~ui

你不需要双倍逃脱\s

PHP代码:

代码语言:javascript
复制
preg_replace('~[^\p{Cyrillic}a-z0-9_\s-]+~ui', '', $string);
票数 2
EN

Stack Overflow用户

发布于 2018-04-16 19:41:14

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

\p{L}\p{Letter}与任何语言中的任何字母相匹配。

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

因为西里尔字符不是标准的ASCII字符,所以您必须使用u标志/修饰符,因此regex将根据需要识别Unicode字符。

在使用unicode字符时,一定要使用mb_strtolower而不是strtolower

因为您将所有字符转换为小写,所以不必使用i regex标志/修饰符。

下面的PHP代码应该适用于您:

代码语言:javascript
复制
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}匹配所有非补充西里尔字符

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49861408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档