使用正则表达式打印文件中字符串的所有出现


Printing all occurences of a string in a file using regular expressions using php

我正在编写一个代码,将从大约500页的文件中打印字符串的所有实例。下面是一些代码:

$file = "serialnumbers.txt";
$file_open = fopen($file, 'r');
$string = "'$txtserial";
$read = fread($file_open,'8000000');
$match_string = preg_match('/^$txtserial/', $read, $matches[]=null);
for($i = 0; sizeof($matches) > $i; $i++)
{
echo "<li>$matches[$i]</li>";
}

所有的序列号都以"$txtserial"开头,后面跟着大约10个数字字符,其中一些用逗号(,)分隔。例如:txtserial0840847276美元,8732569089。实际上,我正在寻找一种方法来打印$txtserial的每个实例,其中包含以下数字字符,不包括逗号(,)。虽然我已经使用了正则表达式,但如果有任何其他方法可以使用,我也会很感激。我只想在最短的时间内完成这件事

你有一个问题,这里你试图创建一个正则表达式使用字符串变量:

$match_string = preg_match('/^$txtserial/', $read, $matches[]=null);

你可以使用:

$match_string = preg_match('/^' . preg_quote($txtserial) . '/', $read, $matches);

使用preg_match_all()函数试试这个例子:

$txtserial = 'MSHKK';
$read = 'MSHKK1231231231,23
MSHKK1231231
txtserial123123109112
MSHKK1231231111,123123123';
$match_string = preg_match_all('/(?:^|(?<=['n'r]))('.preg_quote($txtserial).''d{10})'b/', $read, $matches);
print_r($matches[1]);
输出:

[0] => MSHKK1231231231
[1] => MSHKK1231231111

它基本上是从$txtserial保存的值开始,然后是10数字的部分。