剥离php变量,用破折号替换空格

Rob*_*Rob 68 php

如何将PHP变量从"我的公司和我的名字"转换为"my-company-my-name"?

我需要将它全部小写,删除所有特殊字符并用短划线替换空格.

ror*_*cko 233

此函数将创建一个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;
}
Run Code Online (Sandbox Code Playgroud)

应该没事 :)

  • [这个问题](http://stackoverflow.com/questions/9734970)表明不值得剥离"停止"字样; 我创建了一个[gist](https://gist.github.com/chrisveness/7c34a3f18938f33d513c),它为rory的解决方案添加了重音字符处理. (3认同)

NoL*_*ing 9

替换特定字符:http: //se.php.net/manual/en/function.str-replace.php

例:

function replaceAll($text) { 
    $text = strtolower(htmlentities($text)); 
    $text = str_replace(get_html_translation_table(), "-", $text);
    $text = str_replace(" ", "-", $text);
    $text = preg_replace("/[-]+/i", "-", $text);
    return $text;
}
Run Code Online (Sandbox Code Playgroud)


Pie*_*sin 7

Yop,如果你想处理任何特殊字符,你需要在模式中声明它们,否则它们可能会被刷新.你可以那样做:

strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $string)));
Run Code Online (Sandbox Code Playgroud)