2010-05-02 117 views
1

我試圖將標題數據更改爲URL。我需要從以下動態數據,我從$標題擺脫掉的「大限」開始的所有文字:str_replace問題

紐約截止2010年5月14日(急)
新罕布什爾截止日期5月19日, 2010
新澤西期限

我希望得到的結果應該是這樣的
新約克
新漢普郡
新球衣

這是我曾嘗試

$newurl = strip_tags(str_replace("deadline","","$title")); 
$code_entities_match = array('&quot;' ,'!' ,'@' ,'#' ,'$' ,'%' ,'^' ,'&' ,'*' ,'(' ,')' ,'+' ,'{' ,'}' ,'|' ,':' ,'"' ,'<' ,'>' ,'?' ,'[' ,']' ,'' ,';' ,"'" ,',' ,'.' ,'_' ,'/' ,'*' ,'+' ,'~' ,'`' ,'=' ,' ' ,'---' ,'--','--'); 
$code_entities_replace = array('' ,'-' ,'-' ,'' ,'' ,'' ,'-' ,'-' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'-' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'-' ,'' ,'-' ,'-' ,'' ,'' ,'' ,'' ,'' ,'-' ,'-' ,'-','-'); 
$newtitle = str_replace($code_entities_match, $code_entities_replace, $newurl); 
$urltitle = strtolower($newtitle); 

不幸的代碼,結果是:
新紐約的最後期限-MAY-14-2010緊急
新漢普郡截止日-MAY-19 -2010
new-jersey-

任何人都可以幫忙嗎?

+0

限期部件沒有得到過濾,請你確認嗎? – 2010-05-02 14:33:36

回答

2

可以使用的preg_replace爲:

$str = 'New York deadline May 14th, 2010 (urgent)'; 

$to = array('/deadline.*/','/^\s+|\s+$/','/\s+/'); 
$from = array('','','-'); 
$str = strtolower(preg_replace($to,$from,$str)); 

echo $str; // prints new-york 
+0

這一個也適用,但有(:)的跡象剩下,謝謝 – user330840 2010-05-02 14:43:13

2

這裏有一個非正則表達式的方式

$str = 'New York deadline May 14th, 2010 (urgent)'; 
$title = str_replace(' ', '-', current(explode(' deadline', $str))); 
+0

這是一個不錯的小方法。要完全解決你當然需要將你的'$ title'轉換爲小寫。 – icio 2010-05-02 14:36:22

+0

太棒了!像一個魅力工程...感謝 – user330840 2010-05-02 14:39:22

+0

正確的你應該真的有一個函數,將字符串轉換爲網址。 codeigniter有一個你可以偷。 – Galen 2010-05-02 14:41:09