删除php变量,用破折号替换空白


72

如何将PHP变量从“我的公司和我的名字”转换为“我的公司-我的名字”?

我需要全部小写,删除所有特殊字符,并用破折号代替空格。


Answers:


246

此函数将创建一个SEO友好字符串

function seoUrl($string) {
    //Lower case everything
    $string = strtolower($string);
    //Make alphanumeric (removes all other characters)
    $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
    //Clean up multiple dashes or whitespaces
    $string = preg_replace("/[\s-]+/", " ", $string);
    //Convert whitespaces and underscore to dash
    $string = preg_replace("/[\s_]/", "-", $string);
    return $string;
}

应该没事 :)


1
谢谢。这是一个很好的简单函数,可以扩展以去除某些诸如“ the”和“ and”之类的搜索引擎友好关键字。
rorypicko

4
这个问题表明,不应该删除“停止”字词。我创建了一个要点,在rory的解决方案中添加了重音字符处理。
ChrisV 2014年

如何删除没有-符号的第一个和最后一个空格?
Kvvaradha

@Kvvaradha将以下行粘贴为函数的第一行$string = trim($string);,这将解决您的问题。
Devner '16

如何使用它
AjithChadda


8

是的,如果要处理任何特殊字符,则需要在模式中声明它们,否则它们可能会被冲洗掉。您可以这样做:

strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $string)));
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.