簡體   English   中英

刪除所有特殊字符,但不刪除非拉丁字符

[英]Remove all special chars, but not non-Latin characters

我正在將此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;
}

您需要為西里爾字母使用Unicode腳本,幸運的是PHP PCRE使用\\p{Cyrillic}支持它。 此外,您還必須設置u (unicode)標志來預測引擎行為。 您可能還需要i標志來啟用不區分大小寫的功能,例如AZ

~[^\p{Cyrillic}a-z0-9_\s-]~ui

您無需兩次轉義\\s

PHP代碼:

preg_replace('~[^\p{Cyrillic}a-z0-9_\s-]+~ui', '', $string);

要了解有關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}匹配所有非西里爾字母

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM