[英]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
欢迎大笑:)并感谢您的帮助。
这是一个很好的功能,可以做到这一点:
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.