2015-07-11 44 views
-3

基本上我有一個文本文件,它有多行,如果一行包含我正在尋找的內容,我希望整行。獲取包含東西的整行

例如,這裏是什麼可能是在文本文件中:

Apple1:Banana1:Pear1 
Apple2:Banana2:Pear2 
Apple3:Banana3:Pear3 

如果沒有與Apple2例如一條線,我該如何使用PHP來獲取全線(Apple2:Banana2:Pear2)並將其存儲在一個變量?

+0

你嘗試過什麼嗎? – Rizier123

回答

0

這是我會採取的方法。

$string = 'Apple1:Banana1:Pear1 
Apple2:Banana2:Pear2 
Apple3:Banana3:Pear3 
Apple22:Apple24:Pear2 
Apple2s:Apple24:Pear2'; 
$target = 'Apple2'; 
preg_match_all('~^(.*\b' . preg_quote($target) . '\b.*)$~m', $string, $output); 
print_r($output[1]); 

輸出:

Array 
(
    [0] => Apple2:Banana2:Pear2 
) 

這裏的m修飾是很重要的,php.net/manual/en/reference.pcre.pattern.modifiers.php。正如preg_quote(除非您注意搜索詞),http://php.net/manual/en/function.preg-quote.php

更新:

,要求直接啓動與目標長期使用這個更新的正則表達式。

preg_match_all('~^(' . preg_quote($target) . '\b.*)$~m', $string, $output); 

Regex101演示:https://regex101.com/r/uY0jC6/1

+0

您的答案似乎爲我工作,但你認爲你可以修復它,使它只顯示以Apple2開頭的結果嗎? – user1394913

+0

更新了正則表達式以匹配開始。 – chris85

1
$file = 'text.txt'; 
$lines = file($file); 
$result = null; 
foreach($lines as $line){ 
    if(preg_match('#banana#', $line)){ 
     $result = $line; 
    } 
} 

if ($result == null) { 
    echo 'Not found'; 
} else { 
    echo $result; 
} 
+0

Yann的編輯添加了一個檢查,以防止它試圖回顯一個空的結果:) –

0

我喜歡preg_grep()。這個發現Apple2任何地方:

$lines = file('path/to/file.txt'); 
$result = preg_grep('/Apple2/', $lines); 

這個發現開始Apple2只有條目:

$result = preg_grep('/^Apple2/', $lines); 

沒有與這取決於你想要的圖案很多可能性。在這裏閱讀http://www.regular-expressions.info