获得包含某些内容的整条线

时间:2015-07-11 23:11:34

标签: php php-5.6

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

例如,以下是文本文件中的内容:

Apple1:Banana1:Pear1
Apple2:Banana2:Pear2
Apple3:Banana3:Pear3

例如,如果Apple2中有一行,我怎样才能使用php来获取整行(Apple2:Banana2:Pear2)并将其存储在变量中?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

这是我要采取的一种方法。

$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

答案 2 :(得分:0)

我喜欢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

相关问题