获取包含某些内容的整行

Get whole line that includes something

基本上我有一个包含多行的文本文件,如果某行包含我要查找的内容,我需要整行。

例如,文本文件中可能包含以下内容:

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(除非您对搜索词很小心)一样,http://php.net/manual/en/function.preg-quote.php

更新:

要要求行以目标术语开头,请使用此更新的正则表达式。

preg_match_all('~^(' . preg_quote($target) . '\b.*)$~m', $string, $output);

Regex101 演示:https://regex101.com/r/uY0jC6/1

我喜欢preg_grep()。这会在任何地方找到 Apple2

$lines = file('path/to/file.txt');
$result = preg_grep('/Apple2/', $lines);

这仅查找以 Apple2:

开头的条目
$result = preg_grep('/^Apple2/', $lines);

根据您的需要,图案有多种可能性。阅读此处 http://www.regular-expressions.info