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

使用php使用正则表达式打印文件中出现的所有字符串,php,regex,string,file,Php,Regex,String,File,我正在编写一个代码,它将从一个大约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;

我正在编写一个代码,它将从一个大约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>";
}
$file=“serialnumbers.txt”;
$file_open=fopen($file,'r');
$string=“\$txtserial”;
$read=fread($file_open,'8000000');
$match_string=preg_match('/^$txtsserial/',$read,$matches[]=null);
对于($i=0;sizeof($matches)>$i;$i++)
{
echo“
  • $matches[$i]
  • ”; }
    所有序列号都以“$txtserial”开头,后跟大约10个数字字符,其中一些字符用逗号(,)分隔。示例:$TXTSERIAl084084727632569089。
    实际上,我正在寻找一种方法,用以下数字字符打印$txtserial的每个实例,不包括逗号(,)。虽然我使用过正则表达式,但如果有其他方法可以使用,我也将不胜感激。我只想在尽可能快的时间内完成此操作

    您在尝试使用字符串变量创建正则表达式时遇到问题:

    $match_string = preg_match('/^$txtserial/', $read, $matches[]=null);
    
    您可以使用:

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

    使用
    preg\u match\u 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]);
    

    它基本上是选择以
    $txtserial
    持有的值开始,然后是
    10
    位的部分。

    是否
    $txtserial
    总是在行的开头?
    [0] => MSHKK1231231231
    [1] => MSHKK1231231111