【问题标题】:Generate slug with german umlauts用德语变音符号生成 slug
【发布时间】:2014-11-21 04:28:42
【问题描述】:

我尝试从字符串中生成 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'

【问题讨论】:

    标签: php regex


    【解决方案1】:

    将第二行 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
    

    【讨论】:

    • 我得到了输出'ein-schner-text'。
    • 但我得到了上面的输出。 ö 被翻译成o
    • 我没有收到o。顺便说一句:应该是oe :-)
    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 2011-11-07
    • 2016-01-21
    • 2013-02-09
    • 1970-01-01
    • 2021-09-28
    • 2013-12-25
    • 2016-06-16
    相关资源
    最近更新 更多