2013-07-25 37 views
0

代碼更多:使preg_split匹配比它應該

$pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
    $urls = array(); 
    preg_match($pattern, $comment, $urls); 

    return $urls; 

據一項網上正則表達式測試儀,這正則表達式是正確的,應該工作:

http://regexr.com?35nf9

我輸出$鏈接陣列使用:

$linkItems = $model->getLinksInComment($model->comments); 
//die(print_r($linkItems)); 
echo '<ul>'; 
foreach($linkItems as $link) { 
    echo '<li><a href="'.$link.'">'.$link.'</a></li>'; 
} 
echo '</ul>'; 

輸出如下所示:

的$模型 - >評論如下所示:

destined for surplus 
RT#83015 
RT#83617 
http://google.com 
https://google.com 
non-link 

產生的列表只假設是鏈接,並且不應該有空行。我所做的是否有問題,因爲正則表達式似乎是正確的。

+0

你應該發佈'$ model-> comments' –

+0

@MarkLakata謝謝,這可能會有所幫助。我已編輯它。 – ComputerLocus

+1

正則表達式是Godforsaken暴行,我並不感到驚訝,你不能使它成爲正面或反面;出於可維護性和基本理智的原因,您會非常樂意找到*任何其他方法*將'$ comment'分解爲您需要的值。 –

回答

1

如果我的理解沒錯,你應該在你的getLinksInComment功能使用preg_match_all代替:

preg_match_all($pattern, $comment, $matches); 

if (isset($matches[0])) { 
    return $matches[0]; 
} 
return array(); #in case there are no matches 

preg_match_all獲得所有比賽中的字符串(即使字符串中包含新行),並將它們放入數組你供應作爲第三個參數。但是,正則表達式捕獲組匹配的任何東西(例如(http|https|ftp|ftps))也將被放入您的$matches數組中(如$matches[1]等)。這就是爲什麼你只想返回$matches[0]作爲你最終的比賽陣列。

我只是跑這個確切代碼:

$line = "destined for surplus\n 
RT#83015\n 
RT#83617\n 
http://google.com\n 
https://google.com\n 
non-link"; 

$pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
preg_match_all($pattern, $line, $matches); 

var_dump($matches); 

,並得到了這個對我的輸出:

array(3) { 
    [0]=> 
    array(2) { 
    [0]=> 
    string(17) "http://google.com" 
    [1]=> 
    string(18) "https://google.com" 
    } 
    [1]=> 
    array(2) { 
    [0]=> 
    string(4) "http" 
    [1]=> 
    string(5) "https" 
    } 
    [2]=> 
    array(2) { 
    [0]=> 
    string(0) "" 
    [1]=> 
    string(0) "" 
    } 
} 
+0

我已經實現了這一點,請檢查我的編輯以查看新代碼。問題是現在輸出仍然不正確。它只用了第二個URL的一部分。 – ComputerLocus

+0

@fogest是'$ model-> comments'帶有換行符的字符串?您可能需要使用'preg_match_all'而不是 – sgroves

+0

$ model-> comments是用戶輸入的,所以它可以。使用_all給我一個列表,現在有三個「數組」項。所以它看起來像'* Array * Array * Array'假裝每個數組是新行上的新項目符號。 – ComputerLocus

0

您的評論的結構爲多條線路,其中一些包含的URL中,你」重新感興趣,沒有別的。在這種情況下,您不需要使用任何類似於正則表達式災難的任何東西來嘗試從完整評論文本中挑選URL;您可以改爲按換行符分隔,並分別檢查每行以查看它是否包含URL。因此,你有可能實現一個更可靠getLinksInComment()這樣的:

function getLinksInComment($comment) { 
    $links = array(); 
    foreach (preg_split('/\r?\n/', $comment) as $line) { 
     if (!preg_match('/^http/', $line)) { continue; }; 
     array_push($links, $line); 
    }; 
    return $links; 
}; 

有了適當的調整,作爲一個對象的方法,而不是裸露的功能,這應該完全解決您的問題,並免費你去你的一天。

+0

查看我的評論,我在我的帖子下給你,這是行不通的。 – ComputerLocus

相關問題