gpt4 book ai didi

php - 使用 php 正则表达式查找包含单词的整行

转载 作者:行者123 更新时间:2023-12-04 00:09:02 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

如果我正确解释了您的意图,则您尝试匹配零个或多个 not 换行符,然后是“ session ”,然后是零个或多个 not 换行符。

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

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

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

你已经用 [^\n] 重新发明了 anchor (^$),这有点不明显,但错过了单词边界,这可能是您不希望匹配的 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”这一行。

关于php - 使用 php 正则表达式查找包含单词的整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14675452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com