2011-04-14 171 views
1

請在我的代碼中糾正我。我有一個txt文件幷包含關鍵字。php preg_match不返回結果

example 
aaa 
aac 
aav 
aax 
asd 
fdssa 
fsdf 

我創建了一個用於搜索的php文件。

<?php 
$file = "myfile.txt"; 
if($file) { 
    $read = fopen($file, 'r'); 
    $data = fread($read, filesize($file)); 
    fclose($read); 

    $im = explode("\n", $data); 
    $pattern = "/^aa+$/i"; 

    foreach($im as $val) { 
     preg_match($pattern, $val, $matches); 
    } 
} 
else { 
    echo $file." is not found"; 
} 
?> 
<pre><?php print_r($matches); ?></pre> 

,應返回

aac 
aav 
aax 

它應該返回匹配的單詞。如果單詞從左邊開始有「aa」,則左側有aa的所有單詞都會返回。我想在數組中的結果。 該怎麼辦?請幫助

+0

由於這個原因,你用線拆呢?它只需要正則表達式還是由於某些原因?當preg_match_all()可以在一行中爲你做時, – 2011-04-14 10:52:23

回答

2

你的變量$matches,因爲它得到每個foreach迭代覆蓋僅能將最後匹配嘗試的結果。此外,^aa+$只會匹配由兩個或更多個a組成的字符串。

要獲得僅以aa開頭的字符串匹配,請改爲使用^aa。如果你想所有匹配的行,你需要收集他們在另一個數組:

foreach ($im as $val) { 
    if (preg_match('/^aa/', $val, $match)) { 
     $matches[] = $match; 
    } 
} 

你也可以使用filepreg_grep

$matches = preg_grep('/^aa/', file($file)); 
+0

不使用循環。 – Walf 2011-04-14 12:27:09

+0

這就是我使用...和工作正常..謝謝! – Jorge 2011-04-15 05:12:18

1

代碼:

<?php 
$filePathName = '__regexTest.txt'; 

if (is_file($filePathName)) { 

    $content = file_get_contents($filePathName); 

    $re = '/ 
     \b   # begin of word 
     aa   # begin from aa 
     .*?   # text from aa to end of word 
     \b   # end of word 
     /xm';  // m - multiline search & x - ignore spaces in regex 

    $nMatches = preg_match_all($re, $content, $aMatches); 
} 
else { 
    echo $file." is not found"; 
} 
?> 
<pre><?php print_r($aMatches); ?></pre> 

結果:

Array 
(
    [0] => Array 
     (
      [0] => aaa 
      [1] => aac 
      [2] => aav 
      [3] => aax 
     ) 

) 

它也將努力爲

aac aabssc 
aav 
+0

'$ re ='/ \ baa \ B * /''就足夠了,您只需要'm'來使用'^'和'$'來匹配行的開始和結束。 – Walf 2011-04-14 12:24:41

+0

@Lucas:請檢查,你的正則表達式在PHP中不起作用。 \ B * – 2011-04-14 12:29:39

+0

問題很抱歉,對。 '$ re ='/ \ baa。*?\ b /''是的。 – Walf 2011-04-14 12:48:03