Php 获取包含某些内容的完整行
基本上,我有一个文本文件,有多行,如果一行包括我要找的东西,我想要整行 例如,以下是文本文件中可能包含的内容:Php 获取包含某些内容的完整行,php,php-5.6,Php,Php 5.6,基本上,我有一个文本文件,有多行,如果一行包括我要找的东西,我想要整行 例如,以下是文本文件中可能包含的内容: Apple1:Banana1:Pear1 Apple2:Banana2:Pear2 Apple3:Banana3:Pear3 例如,如果其中有一行包含Apple2,我如何使用php获取整行(Apple2:Banana2:Pear2),并将其存储在变量中?以下是我将采用的方法 $file = 'text.txt'; $lines = file($file); $result = nul
Apple1:Banana1:Pear1
Apple2:Banana2:Pear2
Apple3:Banana3:Pear3
例如,如果其中有一行包含Apple2,我如何使用php获取整行
(Apple2:Banana2:Pear2)
,并将其存储在变量中?以下是我将采用的方法
$file = 'text.txt';
$lines = file($file);
$result = null;
foreach($lines as $line){
if(preg_match('#banana#', $line)){
$result = $line;
}
}
if ($result == null) {
echo 'Not found';
} else {
echo $result;
}
$string = 'Apple1:Banana1:Pear1
Apple2:Banana2:Pear2
Apple3:Banana3:Pear3
Apple22:Apple24:Pear2
Apple2s:Apple24:Pear2';
$target = 'Apple2';
preg_match_all('~^(.*\b' . preg_quote($target) . '\b.*)$~m', $string, $output);
print_r($output[1]);
输出:
Array
(
[0] => Apple2:Banana2:Pear2
)
这里的m
修饰符很重要,php.net/manual/en/reference.pcre.pattern.modifiers.php。正如preg_quote
(除非您小心搜索词)
更新:
要要求行以目标术语开头,请使用此更新的正则表达式
preg_match_all('~^(' . preg_quote($target) . '\b.*)$~m', $string, $output);
Regex101演示:我喜欢preg\u grep()
。这会在任何地方找到Apple2
:
$lines = file('path/to/file.txt');
$result = preg_grep('/Apple2/', $lines);
这将仅查找以Apple2
开头的条目:
$result = preg_grep('/^Apple2/', $lines);
根据您的需要,该模式有许多可能性。阅读此处您尝试过什么吗?Yann的编辑添加了一个检查,以防止它尝试回显空结果:)您的答案似乎对我有效,但您认为您可以修复它,使其仅显示以Apple2开头的结果吗?请更新正则表达式以匹配开头。