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?

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.