【问题标题】:Find whole line that contains word with php regular expressions使用 php 正则表达式查找包含单词的整行
【发布时间】:2013-02-04 02:28:33
【问题描述】:

我想在文本中搜索单词“会话”。但我想检索出现这个词的整行。到目前为止,我已经想出了这个。

$pattern="[^\\n]*session[^\\n]*";
preg_match_all($pattern,$content, $matches, PREG_OFFSET_CAPTURE);

但我收到错误“未知修饰符'*'”。任何想法如何制作这样的正则表达式?

【问题讨论】:

    标签: php regex line preg-match-all


    【解决方案1】:

    您的正则表达式缺少分隔符,因此您的错误:

    $pattern = "/[^\\n]*session[^\\n]*/";
    // or, with single quotes, you don't need to escape \n
    $pattern = '/[^\n]*session[^\n]*/';
    

    如果我正确地解释了你的意图,你会尝试匹配零个或多个 not 换行符,然后是“会话”,然后是零个或多个 not em> 换行符。

    一个更简单(可能更正确)的模式是这样的:

    $pattern = '/^.*\bsession\b.*$/m';
    

    也就是说,从一行的开头(^)匹配0个或多个任意字符(.*),一个单词边界(\b),单词“session”,另一个单词边界,另一系列字符,以及行尾 ($),匹配多行(m 修饰符)。

    您已经用[^\n] 重新发明了锚点(^$),这有点不明显,但错过了单词边界,这可能是不希望的,因为您正在匹配any word that contains the word "session" .也就是说,你的会匹配包含“sessions”或“possessions”或“obsessions”或“abcsessionxyz”的行,而我的不会;如果不希望这样做,您可以删除 \b 产生的 /^.*session.*$/m,我们的模式将或多或少等效。

    这是一个概念验证,找到包含单词的整个中间行:

    <?php
    
    $lines ="This is a test
    of skipping the word obsessions but
    finding the word session in a
    bunch of lines of text";
    
    $pattern = "/^.*\bsession\b.*$/m";
    
    $matches = array();
    preg_match($pattern, $lines, $matches);
    
    var_dump($matches);
    

    输出:

    array(1) {
      [0]=>
      string(29) "finding the word session in a"
    }
    

    您的模式会找到“跳过单词 obsessions but”这一行。

    【讨论】:

    • 谢谢,我有一个问题 \b(boundary) 到底是什么?这不是空白,我知道的就这么多。
    • 字边界被描述为here,但基本上在两个字符之间的任何地方,一个是字字符([a-zA-Z0-9_]),一个不是。值得注意的是,我们的模式并不相同。你的会匹配“blahsessionblah”,而我的不会。
    • @BorutFlis 更新了我的答案,以说明为什么词边界很重要。
    猜你喜欢
    • 2016-12-07
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多