开发者

php preg_match returns no result

please correct me in my code. i have a txt file and contains the keywords.

example
aaa
aac
aav
aax
asd
fdssa
fsdf

and I created a php file for search.

<?php
$file = "myfile.txt";
if($file) {
    $read = f开发者_JAVA技巧open($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>

this should return

aac
aav
aax

it should return a match word. if word has "aa" in from the left all words that has aa in the left will return back. and i want the result in array. how to do that? please help


Your variable $matches will only hold the result of the last matching attempt as it gets overwritten with each foreach iteration. Furthermore, ^aa+$ will only match strings that consists of two or more as.

To get a match for strings that only start with aa, use just ^aa instead. And if you want all matching lines, you need to collect them in another array:

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

You could also use file and preg_grep:

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


Code:

<?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>

Result:

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

)

It will work also for

aac  aabssc
aav
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜