【问题标题】:How can I replace ":" with "/" in slugify function?如何在 slugify 函数中将“:”替换为“/”?
【发布时间】:2012-05-14 02:55:31
【问题描述】:

我有一个对文本进行 slugifying 的函数,它运行良好,只是我需要用“/”替换“:”。目前它用“-”替换所有非字母或数字。这里是:

function slugify($text)
    {
        // replace non letter or digits by -
        $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

        // trim
        $text = trim($text, '-');

        // transliterate
        if (function_exists('iconv'))
        {
            $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        }

        // lowercase
        $text = strtolower($text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        if (empty($text))
        {
            return 'n-a';
        }

        return $text;
    }

【问题讨论】:

    标签: php regex


    【解决方案1】:

    我只做了一些修改。我提供了一组搜索/替换数组,让我们用- 替换大部分内容,但用/ 替换:

    $search = array( '~[^\\pL\d:]+~u', '~:~' );
    $replace = array( '-', '/' );
    $text = preg_replace( $search, $replace, $text);
    

    后来,最后一个preg_replace 将我们的/ 替换为一个空字符串。所以我允许在字符类中使用正斜杠。

    $text = preg_replace('~[^-\w\/]+~', '', $text);
    

    输出如下:

    // antiques/antiquities
    echo slugify( "Antiques:Antiquities" );
    

    【讨论】:

    • 是的,我知道,但是 slugify 函数呢?我的意思是,如果我只想用“/”替换“:”,我可以简单地做一个 str_replace,但我仍然需要对字符串进行 slugify(删除特殊字符等),除了“:”应该替换为“/”而不是“-”。
    • @mihai 你把它放在 slugify 函数中,作为过程的一部分。
    • 不起作用。 “:”仍然被“ - ”取代。我认为这是有道理的,因为我们有 $text = preg_replace('~[^\\pL\d]+~u', '-', $text);不是吗?
    • @mihai 你将什么字符串传递给 slugify?
    • $text = 'Antiques:Antiquities';回声 slugify($text);我得到古董-古董
    猜你喜欢
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2016-11-09
    • 2014-05-12
    • 1970-01-01
    • 2020-02-02
    • 2017-08-12
    相关资源
    最近更新 更多