【问题标题】:Get whole line that includes something [closed]获取包含某些内容的整行 [关闭]
【发布时间】:2015-09-30 12:02:15
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你试过了吗?

标签: php php-5.6


【解决方案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;
}

【讨论】:

  • Yann 的编辑添加了一个检查,以防止它尝试回显空结果:)
【解决方案2】:

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

$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

【讨论】:

  • 你的回答似乎对我有用,但你认为你可以修复它,让它只显示以 Apple2 开头的结果吗?
  • 更新正则表达式以匹配开始。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2021-10-20
    • 2012-05-05
    • 2013-01-20
    • 2016-09-28
    • 2013-04-02
    相关资源
    最近更新 更多