doulu4203 2018-10-08 11:02
浏览 39
已采纳

PHP preg_replace标题(非英文字符)来清理slug无法正常工作

I'm attempting to turn Titles to slugs

$string = "آزمون پادشاهی متحده";
$pattern = '/[`~!@#$%^&*()_|+\=?;:..’“\'"<>,€£¥•،٫؟»«\{\}\[\]\\\/]+/gi';
            $replacement = '';

            $slug = trim(preg_replace($pattern, $replacement, $string));
            $slug = str_replace(" ","-",$slug);

The end result should be آزمون-پادشاهی-متحده spaces replaced by hyphen.

Another example title: Great Britain slug: great-britain

How do i solve?

  • 写回答

1条回答 默认 最新

  • doujiunai2169 2018-10-08 11:17
    关注

    You need to apply the following fixes here:

    • Escape the backslash matching pattern, that is, '\\\\'
    • Remove the g modifier as it is not supported by PHP preg_replace (it replaces all occurrence in the input by default)
    • Add a u modifier to enable PCRE engine to parse both the pattern and input as Unicode strings.

    Use

    $string = "آزمون پادشاهی متحده";
    $pattern = '/[`~!@#$%^&*()_|+=?;:..’“\'"<>,€£¥•،٫؟»«{}[\]\\\\\/]+/ui';
    $replacement = '';
    
     $slug = trim(preg_replace($pattern, $replacement, $string));
     $slug = str_replace(" ","-",$slug);
     echo $slug;
    

    See the PHP demo.

    Note that [, =, { and } are not special inside a character class and need no escaping.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?