我尝试从字符串生成一个 slug,但我在使用德语变音符号时遇到了一些问题:
$text = 'Ein schöner Text';
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
$text = trim($text, '-');
$text = iconv('utf-8', 'ASCII//TRANSLIT', $text);
$text = strtolower($text);
$text = preg_replace('~[^-\w]+~', '', $text);
结果应该是:'ein-schoener-text'
最佳答案
将第二个 preg_replace 行更改为以下内容,因为要匹配任何语言的任何字母,您需要使用 \p{L}
模式。
$text = preg_replace('~[^\p{L}\d]+~u', '-', $text);
代码:
<?php
$text = 'Ein schöner Text';
$text = preg_replace('~[^\p{L}\d]+~u', '-', $text);
$text = trim($text, '-');
$text = iconv('utf-8', 'ASCII//TRANSLIT', $text);
$text = strtolower($text);
$text = preg_replace('~[^-\w]+~', '', $text);
echo $text;
?>
输出:
ein-schoner-text
关于php - 用德语变音符号生成 slug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26054846/