-3

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

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

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

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

4

3 回答 3

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;
}
于 2015-07-11T23:21:18.760 回答
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);

正则表达式 101 演示: https ://regex101.com/r/uY0jC6/1

于 2015-07-11T23:25:08.933 回答
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

于 2015-07-11T23:25:58.997 回答