1

嗨,第一次处理 preg_replace,发现特别难理解的学习者。

尝试将标题字符串更改为 slug 以用于 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

随意大笑:)并感谢您的帮助。

4

3 回答 3

3

Check out this tutorial for a clean URL generator, or even use this existing SO solution which eschews regular expressions altogether. This will probably get the job done:

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);
}
于 2013-01-27T18:53:02.090 回答
2

这是一个很好的功能

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;
}
于 2013-01-27T18:51:27.853 回答
1

Try this:

$string = strtolower($string);
$string = preg_replace("/\W+/", "-", $string); // \W = any "non-word" character
$string = trim($string, "-");
于 2013-01-27T18:53:48.160 回答