简体   繁体   English

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

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

i am writing a code that will print all instances of a string from a file of about 500 pages. 我正在编写代码,该代码将打印约500页文件中字符串的所有实例。 This is some of the code: 这是一些代码:

$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>";
}

All of the serial numbers start with "$txtserial" followed by about 10 numerical characters, some of them separated by comma(,). 所有序列号均以“ $ txtserial”开头,后跟约10个数字字符,其中一些用逗号分隔。 Example: $txtserial0840847276,8732569089. 例如:$ txtserial0840847276,8732569089。 I am actually looking for a way to print every instances of the $txtserial with the following numerical characters excluding the comma(,). 我实际上正在寻找一种使用以下数字字符(不包括逗号)来打印$ txtserial的每个实例的方法。 Though I have used regular expressions but if there is any other method to employ i will also be grateful. 虽然我使用过正则表达式,但是如果有其他使用方法,我也将不胜感激。 I just want to get this done in the quickest possible time 我只想在最快的时间内完成

You have a problem here where you are trying to create a regex using string variable: 您在尝试使用字符串变量创建正则表达式时遇到问题:

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

You can use: 您可以使用:

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

Try this example using preg_match_all() function: 使用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]);

Output: 输出:

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

It is basically picking the portions which are starts with the value that $txtserial holds and followed by 10 digits. 基本上是选择以$txtserial保存的值$txtserial ,然后是10位数字的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM