2012-05-14 26 views
1

我有一個PHP preg_match函數實現,其中我將一個已知的RegEx與另一個變量的清理版本進行比較。我正在使用多個preg_replace等命令進行清理。我想知道是否有一種替代方法可以做到更小的(也許只涉及一個reg匹配)並且更快(匹配多次比一次只做一次更復雜)。將多個正則表達式(匹配和替換)組合成一個正則表達式;優化速度

這裏是我當前的代碼:

$url_regex_to_match = /SOME_REGEX/; //I will pick this from DB 

$matches = array(); 

//Following to replace http://www.google.com into http://google.com 
preg_match('/(http.?):\/\/(www\.)?(.*)/i', $url, $matches); 
if(sizeof($matches)==4) { 
    $url = $matches[1]."://".$matches[3]; 
} 
//Incase the preg_match is false (http is missing), we still need to remove www. 
$url = preg_replace("/(^\*?|\/\/)www\./i","$1",$url); 

//It converts google.com/a#mno into google.com/a 
$url = preg_replace('/^(.*)(#.*)$/', '$1', $url); 
//It converts pages like google.com/index.htm into google.com/ 
$url = preg_replace('/^(.*\/)((home|default|index)\..{3,4})(\?.*)*$/', '$1$4', $url); 
//This will replace google.com/ into google.com 
if(substr($url, -1) == "/") { 
    $url = substr($url, 0, -1); 
} 

//This is just to match the new URLs with the pattern I have 
$boolean = preg_match($url_regex_to_match , $url); 

布爾的期望值是ofcourse真/假。

謝謝

+0

你可能會添加一些解釋預期結果的註釋嗎? –

+0

對不起,我添加了一些評論。讓我知道如果你希望它更清晰 –

+1

所以,你想提取URL的域名部分?您可能應該使用URL解析庫來代替試圖推出您自己的基於正則表達式的解決方案;有很多URL可能會讓你感覺不適。查看PHP的['parse_url()'](http://php.net/manual/en/function.parse-url.php)。 –

回答

0

我想知道你到底想要什麼。我的意思是提取域可以在一個新的正則表達式就像這樣:

preg_replace/http[s]*:\/\/[\w\d\.-]*\.([\d\w-]*)\..+\/(.*)/i,"$1") 

所以基本上我的答案是:建立一個正則表達式您的問題,而不是很多。我看不出有什麼辦法可以做,因爲另一種方式基本上需要計算機瞭解正則表達式搜索的內容並將它們放在一起(這很可能導致正則表達式更慢)。如果我的解決方案無法幫助您,請在評論中告知我。

編輯:對不起,我澄清了我的正則表達式。

+0

不幸的是,這不起作用。它不符合我原來的問題的邏輯,而且在子域的情況下不會給出預期的答案。 –

+0

我騙了我的正則表達式。我認爲正則表達式會輸出相同的,不管是否php,新的甚至輸出正確的域「http://mail35.5-5mail.go23o4-gl1e.com/calendar/index.htm」' – javex