2012-07-04 64 views
55

如何将一个PHP变量从“My company & My Name”转换为“my-company-my-name”?去掉php变量,用破折号替换空格

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

+5

[你尝试过什么?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – ManseUK

回答

195

此功能将创建一个搜索引擎友好的字符串

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

应该罚款:)

+3

+1完美的片断: ) – Mahdi

+1

谢谢。这是一个很好的简单功能,它可以扩展去除某些不适合使用的关键字,比如'the'&'和'。 – rorypicko

+0

当然,它确实工作正常,它值得延长! – Mahdi

8

更换特定的字符: 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; 
} 
6

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

strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $string))); 
相关问题