2012-01-25 32 views
2

我試圖使用正則表達式與使preg_split到URL從一個字符串中分離:PHP使preg_split()沒有捕捉分割字符串中

$body = "blah blah blah http://localhost/tomato/veggie?=32"; 
    $regex = "(((f|ht){1}tp://)[[email protected]:%_\+.~#?&//=]+)"; 
    $url = preg_split($regex, $body); 

所得陣列是:

array(2) (
    [0] => (string) blah blah blah 
    [1] => (string)) 

我想回:

array(2) (
    [0] => (string) blah blah blah 
    [1] => (string) http://localhost/tomato/veggie?=32) 

不知道我在做什麼錯在這裏...任何建議將不勝感激。

回答

3

嘗試添加另一組括號來捕捉帶有可選使preg_split()的參數整網址:

$regex = "((((f|ht){1}tp://)[[email protected]:%_\+.~#?&//=]+))"; 
$url = preg_split($regex, $body, null, PREG_SPLIT_DELIM_CAPTURE); 

輸出:

array(5) { 
    [0]=> 
    string(15) "blah blah blah " 
    [1]=> 
    string(34) "http://localhost/tomato/veggie?=32" 
    [2]=> 
    string(7) "http://" 
    [3]=> 
    string(2) "ht" 
    [4]=> 
    string(0) "" 
} 
+0

你可以添加2個非cature組清理輸出像這樣'(((:(?: F | HT){1? } tp://)[-a-zA-Z0-9 @:%_ \ +。〜#?&// =] +))' - 從數組中取出[2]和[3] 。 ':)' – Biotox

+0

非常感謝!同樣,優秀的輸入Biotox – Akersh

1

它的失敗,因爲你是在一個URL分裂,不在分隔符上。在這種情況下,分隔符是「FTP或HTTP前的最後空間」:

$body = "blah blah blah http://localhost/tomato/veggie?=32"; 
$regex = '/\s+(?=(f|ht)tp:\/\/)/'; 
$url = preg_split($regex, $body); 

要打破正則表達式:

\s+ - One or more spaces 
(?=...) - Positive look-ahead (match stuff in this group, but don't consume it) 
(f|ht)tp:\/\/ - ftp:// or http:// 
+0

如果URL後面有一個單詞,比如'blah blah blah http:// localhost/tomato/veggie?= 32 test',它會被添加到URL中。 'array([0] =>'blah blah blah',[1] =>'http:// localhost/tomato/veggie?= 32 test')' – Biotox

+0

確實。幸運的是,這不適用於這種情況。 –

0

的第一個問題是,你的正則表達式是不是delimited(即不被斜線包圍)。

第二個問題是,考慮到您提供的樣本輸出,您可能需要考慮使用preg_match來代替。

試試這個,看它是否是你想要什麼:

$body = "blah blah blah http://localhost/tomato/veggie?=32"; 
$regex = "/^(.*?)((?:(?:f|ht)tps?:\/\/).+)/i"; 
preg_match($regex, $body, $url); 
print_r($url);