preg_replace:试图理解将标题作为url的slug

时间:2013-01-27 18:48:05

标签: php preg-replace

嗨,第一次与preg_replace打交道,发现该死的复杂情况,特别是了解学习者。

尝试将标题字符串更改为slug for url结构,删除所有特殊字符,例如( ) ? *,并将多个空格替换为单-,并将所有文本转换为小写。

这是我有趣的代码但没有获得欲望输出。

$title_slug = $q_slug->title;
$title_slug = preg_replace("/[\s+\?]/", " ", $title_slug);        
$title_slug = str_replace("  ", " ", $title_slug);
$title_slug = str_replace(" ", "-", $title_slug);
$title_slug = preg_replace("/[^\w^\_]/"," ",$title_slug);
$title_slug = preg_replace("/\s+/", "-", $title_slug);
$title_slug = strtolower($title_slug);

return $title_slug;

编辑:添加了示例

示例:if my title is what is * the() wonder_ful not good?? and where??? 结果:if-my-title-is-what-is-the-wonder_ful-not-good-and-where

随意笑:)和万万感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

查看this tutorial以获取干净的网址生成器,甚至可以使用完全避开正则表达式的this existing SO solution。这可能会完成工作:

function toAscii($str) {
   $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
   $clean = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $clean);
   $clean = strtolower(trim($clean, '-'));
   return preg_replace("/[\/_| -]+/", '-', $clean);
}

答案 1 :(得分:2)

以下a nice function就是这样做的:

function toSlug ($string) {
        $string = strtolower($string);
        // Strip any unwanted characters
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        // Clean multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);
        // Convert whitespaces and underscore to dash
        $string = preg_replace("/[\s_]/", "-", $string);

        return $string;
}

答案 2 :(得分:1)

试试这个:

$string = strtolower($string);
$string = preg_replace("/\W+/", "-", $string); // \W = any "non-word" character
$string = trim($string, "-");