【问题标题】:PHP Remove Punctuation (No Dashes)PHP 删除标点符号(无破折号)
【发布时间】:2012-12-30 16:05:43
【问题描述】:

我在 stackoverflow 上找到了下面的脚本,它用破折号替换了特殊字符,以建立干净的 url。但是,它做得不好,因为它用破折号代替标点符号,如下面的“坏”示例所示。所以,相反,我希望明确标点符号不要被任何东西替换,而是要被删除......没有空格,没有破折号。对此的任何帮助将不胜感激。

示例:

今天天气很热!

好:

今天天气很热

不好:

今天天气很热-

这个脚本做了不好的例子......如何让它做好?:

function slugUrl($string) {
    $string = strtolower($string);
    $string = preg_replace('/[^a-zA-Z0-9]/i','-',$string);
    $string = preg_replace("/(-){2,}/",'$1',$string);
    return $string;
}

【问题讨论】:

    标签: php replace character


    【解决方案1】:

    这个呢? (我只是先去掉了标点符号)

    function slugUrl($string){
        $string = strtolower($string);
        $string = preg_replace('/[!?\']/','',$string);
        $string = preg_replace('/[^a-zA-Z0-9]/i','-',$string);
        $string = preg_replace("/(-){2,}/",'$1',$string);
        return $string;
    }
    

    【讨论】:

    • 我也会先trim() 空格。
    • 呸...为什么不呢。好主意。这里有很多需要改进的地方。
    • 是的,它仍然给出“坏”的结果。如何在这里使用 trim()?
    • 它会带来什么样的坏结果?
    • today's weather is hot 变为 todays-weather-is-hot- 因为尾随空格或某些非字母数字、非 !?' 字符。多一行$string = trim($string, '-'); 应该可以解决这个问题。
    【解决方案2】:

    您可以通过首先删除所有您不感兴趣的字符然后只用破折号替换空格来实现这一点。

    另外preg_replace 允许在使用数组时同时运行多个替换操作 (Demo):

    $subject = 'today\'s weather is hot!';
    
    $buffer = trim(strtolower($subject));
    $result = preg_replace(['/[^a-z0-9 ]/', '/\s+/'], ['', '-'], $buffer);
    

    结果(不带引号):

    "todays-weather-is-hot"
    

    函数形式:

    function slugUrl($string){
        return preg_replace(
            array('/[^a-z0-9 ]/', '/\s+/'), 
            array(''            , '-'    ), 
            trim(strtolower($string))
         );
    }
    

    【讨论】:

    • 哦,我喜欢这个。我也要试试这个。
    • 是的,如果你没有当前稳定的 PHP 5.4 版本,你需要使用array(...) 而不是[...],这是为了简洁我在这里使用的更现代的 PHP 表示法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2011-08-25
    • 1970-01-01
    • 2016-06-07
    相关资源
    最近更新 更多