2014-04-18 26 views
2

我正在編寫一個自定義的博客腳本,並且作爲它的一部分,我正在使用用於發佈URL的slug。我有它的代碼到目前爲止是需要函數的輕微修改

public function get_slug($str) { 
    // convert to lowercase 
    $str = strtolower($str); 
    // remove special chars 
    $str = preg_replace('/[^a-zA-Z0-9]/i', ' ', $str); 
    // remove what space from beginning and end 
    $str = trim($str); 
    // remove repeat spaces 
    $str = preg_replace('/\s+/', ' ', $str); 
    // replace spaces with hyphens 
    $str = preg_replace('/\s+/', '-', $str); 

    return $str; 
} 

這偉大工程的大部分地區,但是如果在字中間的特殊字符它只是用連字符轉向「可以代替它,我已經注意到't'into'can-t'而不是'can not'

雖然在預設情況下,我可以編輯數據庫並手動修復它,我想自動從字的中間去掉特殊字符,不要用炒作來代替它們。

+1

退房[此功能(http://stackoverflow.com/questions/3230012/:

$str = preg_replace('/[^a-zA-Z0-9]/i', ' ', $str); 

上述前將這個用它們的對應物替換口音/ 3230193#3230193)作爲這一個的潛在替代品。 –

+1

嘗試在第一次替換中將空格更改爲空字符串。 – Luigi

回答

2

嘗試改變:

$str = preg_replace('/[^a-zA-Z0-9]/i', ' ', $str); 

到:

$str = preg_replace('/[^a-z0-9\s]/i', '', $str); 

這會不會把空間讓你不希望他們,但允許已經存在的那些留(現在)。那麼你不會在文字中間有空格。 (我也從你的正則表達式中取出了A-Z,因爲它不是必須的,因爲字符串已經是小寫字母,並且你也使用i修飾符,這使得它不區分大小寫)。

+0

感謝@John,仍然是PHP新手,對於正則表達式非常新,已經從教程中獲得了這一點。 – Railto

0

你更換'這裏:

$str = preg_replace("/'/i", '', $str);