2012-06-06 28 views
0

我有一個字符串搜索字符串,我需要搜索這個字符串,並能夠詳細地址分配給一個變量:使用正則表達式PHP

它的外觀在字符串中

infoone:"infoone"infotwo:"infotwo"address:"123 fake street pretend land"infothree:"infothree"infofour:"infofour" address:"345 fake street pretend land"infofive: "infofive"infosix: "infosix" 

我如何使用正則表達式來搜索這個字符串,以便在字地址之後僅提取引號中的數據?

注意:我無法定位短語「123 fake street pretend land」,因爲這只是一個例子,可能是引號中的內容。

+0

你有一個多行字符串(與它的所有行) ?或者每一行都是一個單獨的字符串? – ash108

+0

它實際上只是一個相當龐大的字符串,我已經改變了這個問題。 –

回答

1

使用這個表達式

$str='infoone:"infoone"infotwo:"infotwo"address:"123 fake street pretend land"infothree:"infothree"infofour:"infofour" address:"345 fake street pretend land"infofive: "infofive"infosix: "infosix"'; 

preg_match_all("/address:\"(.*)\"/siU",$str,$out); 
print_r($out[1]); 
1

那麼,正則表達式本身應該是^address:"(.*)"$

顯然,您需要添加相關的preg_match()調用。

+0

難道你不需要設置選項,以便^匹配在PHP的一行開始? – buckley

+0

@buckley不,我不認爲有必要。 – ash108

2

這是一個很好的正則表達式

^address:"([^"]*) 

這是它在PHP與選項,這樣^在該行的開頭匹配,我們舉了1組

preg_match_all('/^address:"([^"]*)/m', $subject, $result, PREG_PATTERN_ORDER); 
$result = $result[1]; 

更新1

preg_match_all('/^address:"([^"]*)/m', $subject, $result, PREG_SET_ORDER); 
for ($matchi = 0; $matchi < count($result); $matchi++) { 
    for ($backrefi = 0; $backrefi < count($result[$matchi]); $backrefi++) { 
     # Matched text = $result[$matchi][$backrefi]; 
    } 
} 

更新2

有了新的採樣輸入剛剛離開的^在開始的時候,使其成爲

address:"([^"]*) 
+0

這將失敗的一個(虛構)例子是:'address:「a \」123 \「house」'。然而,OP沒有具體說明這是否可能。 – ash108

+1

是的,我可以想到更多的邊緣情況(字符串中的換行符,地址中的大寫字母等)。但是應該提到這些應該提到 – buckley

+0

這似乎在某種程度上起作用,我所包含的字符串不止一次由於某些原因有不同的值,這不是在字符串中找到第一個值。我只是稍微編輯我的問題,以使我想要做得更清楚,如果有幫助的話。 –