【发布时间】:2022-01-11 18:47:37
【问题描述】:
我有一个 PHP 脚本,它使用 preg_match_all 函数从文本文件中返回所有匹配项。但是,我希望该函数仅在每行中检查从位置 3 开始且长度为 11 位(基本上,结束位置为 13)的匹配,而不是在整行中查找匹配,因为这将返回错误结果.
脚本:
<?php
$file = 'masterfile.out';
$searchfor = '02354098780';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurrences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo substr(implode("\n", $matches[0]),2,11);
echo substr(implode("\n", $matches[0]),166,11);
}
else{
echo "No matches found";
}
?>
文本文件示例数据:
I0023540987805R01 ABC GHI OLirrt 000000000000000100EA 0812160070451700 1098833 1990041300000001086000000000108600000000000996000000000032100000000000000000000000000000000000000000000000000000000000000000000006589000000000000000 P0012B
0000002032902R01 DEF JKL KLijuI 000000000000000100EA 0812160070451700 1029132 1997010800000002396000000000239600000120002326000000000000000000000000000000000000000000000000000000000000004560000000000000000000000000987600000000 A203SD
【问题讨论】:
-
你能把文本文件的内容贴出来吗?
-
@tcj 当然,我将其添加到帖子中。
-
我的文本文件例子02354098780是否存在?它应该出现在哪里?在任何行起始位置 3 是吗?另外,示例中的行在哪里结束?on : P0012B?
-
@Shlomtzion 是的,值:02354098780 可以在从位置 3 开始的第 1 行找到。第 1 行在 P0012B 结束。在给定的示例中,第 2 行从 0000002032902R01 开始。