繁体   English   中英

preg_replace:试图理解使标题成为url的一部分

[英]preg_replace: trying to understand to make title as a slug for url

嗨,第一次处理preg_replace并发现该死的复合体专门了解学习者。

尝试将标题字符串更改为适用于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??? 结果: if-my-title-is-what-is-the-wonder_ful-not-good-and-where

欢迎大笑:)并感谢您的帮助。

请查看本教程 ,以获取干净的URL生成器,甚至使用完全避开正则表达式的现有SO解决方案 这可能会完成工作:

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);
}

这是一个很好的功能,可以做到这一点:

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;
}

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM