2011-04-14 172 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