2013-06-25 99 views
1

搜索字符串我有一個大的文本:句子/單詞

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tempor 
faucibus eros. Fusce ac lectus at risus pretium tempor. Curabitur vulputate 
eu nibh at consequat. find'someword' Curabitur id ipsum eget massa condimentum pulvinar in 
ac purus. Donec sollicitudin eros ornare ultricies tristique. find'someword2' Sed condimentum 
eros a ante tincidunt dignissim. 

什麼是搜索的字符串,返回字其間輸入引號的最簡單的方法?

到目前爲止,我已經試過這樣:

$findme = array('find'); 
$hay = file_get_contents('text.txt'); 


foreach($findme as $needle){ 

    $search = strpos($hay, $needle); 

    if($search !== false){ 
     //Return word inbetween apostrophe 
    } 
} 

我知道總會有字的撇號前右找到。

回答

5

爲什麼不直接使用正則表達式?

if(preg_match_all("/find'(.+?)'/", $hay, $matches)) { 
    array_shift($matches); 
    print_r($matches); 
} 
else { 
    //no matches 
} 

UPDATE:如果字符串「找到」是不固定的,你可以在它的位置使用變量,而且,你可以很容易地分隔多個單詞:

$prefix = "find|anotherword"; 
if(preg_match_all("/($prefix)'(.+?)'/", $hay, $matches)) { 
    $matches = $matches[2]; 
    print_r($matches); 
} 
else { 
    //no matches found 
} 
+0

*一個人一次試圖用正則表達式解決問題。然後他有兩個。* –

+1

@NielsKeurentjes我坦率地不理解你的評論的相關性。他正在尋找字符串內的特定匹配 - 這正是正則表達式的用途。如果你知道你在做什麼,那麼你將解決問題,而不是創造更多的問題。在這種情況下,這個問題是微不足道的。 –

+0

如果我正確地理解了這個問題,'find'字符串是可配置的或者取決於環境,否則爲什麼要使用數組。所以字符串也可能包含有問題的單詞,因此需要轉義等。如果OP對正則表達式有足夠的瞭解,他會選擇這個解決方案,顯然他沒有,這可能會導致很多問題。而且,regexps在計算上比簡單的'strpos'調用要昂貴得多。我主要試圖說正則表達式應該避免,除非它們可以捍衛最好的解決方案。 –