我正在从文本文件中获取数据。如何获取两个分隔符之间的值,即 |根据比赛。前 7 个字符是 id 的一部分。
输入示例:
0123456|BHKAHHHHkk|12345678|JuiKKK121255
9100450|HHkk|12348888|JuiKKK10000000021sdadad255
期望的输出:
BHKAHHHHkk
基于 searchfor
值 = 0123456
我的脚本:
$file = 'file.txt';
// 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
$txt = explode("\n",$contents);
$counter = 0;
foreach($txt as $key => $line){
$subbedString = substr($line,2,6);
// $searchfor = '0123456';
//echo strpos($subbedString,$searchfor);
if(strpos($subbedString,$searchfor) === 0){
$matches[$key] = $searchfor;
echo "<p>" . $matches[$key] . "</p>";
$counter += 1;
if($counter==10) break;
}
最佳答案
preg_match
函数可以用于此目的,它使您的代码非常简单且可读。
每行数据都以 \n
或内容的开头开始,因此使用 \n|^
作为模式的开头;另外 ?:
用于防止在 $matchs
变量中列出此部分。
每行数据以\n
或内容结束结尾,因此使用\n|$
作为模式的结尾; \r
可能出现,也可能不出现,所以 (?:\r?\n|$)
在末尾使用。
$searchfor
变量可以直接位于模式中。
\|([^\n]+)
搜索分隔符和其余行数据。
最后,可以在 $matchs[1]
变量中访问数据的第二个参数(您要查找的数据),而其余数据则在 $matchs 中访问[2]
变量。
<?php
$contents = '0123456|BHKAHHHHkk|12345678|JuiKKK121255
9100450|HHkk|12348888|JuiKKK10000000021sdadad255';
$searchfor = '9100450';
if(preg_match('/(?:\n|^)' . $searchfor . '\|([^|]+)(.*?)(?:\r?\n|$)/is', $contents, $matchs))
{
$second_value = $matchs[1];
$reset_values = $matchs[2];
echo "Result for searching <b>$searchfor</b> is <b>$second_value</b> and reset of data is <b>$reset_values</b>";
}
else echo('Not Found :(');
?>
关于php - 如何使用正则表达式输出两个分隔符之间的字符串中的第二个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70358174/