php preg_match不返回任何结果
请更正我的密码。我有一个txt文件,包含关键字php preg_match不返回任何结果,php,regex,Php,Regex,请更正我的密码。我有一个txt文件,包含关键字 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);
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>
它应该返回一个匹配的单词。如果单词左边有“aa”,所有左边有aa的单词都会返回。我想要数组中的结果。
怎么做?请帮助您的变量$matches将只保存上次匹配尝试的结果,因为每次迭代都会覆盖该结果。此外,
^aa+$
将只匹配由两个或多个a
s组成的字符串
要获取仅以aa
开头的字符串的匹配,请使用^aa
。如果需要所有匹配行,则需要在另一个数组中收集它们:
$matches = preg_grep('/^aa/', file($file));
您还可以使用和:
代码:
Array
(
[0] => Array
(
[0] => aaa
[1] => aac
[2] => aav
[3] => aax
)
)
它也适用于
你为什么要把它分成几行?它只需要正则表达式还是出于某种原因?
$re='/\baa\B*/'
就足够了,您只需要m
就可以使用^
和$
来匹配行的开头和结尾。@Lucas:请检查,您的正则表达式在PHP中不起作用。当preg\u match\u all()可以在一行中完成时,\B*不使用循环的问题。
$matches = preg_grep('/^aa/', file($file));
<?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