使用preg_replace在匹配之前/之后获取字符

我有以下代码可以在正则表达式匹配之前/之后获取字符:

$searchterm = 'blue';
$string = 'Here is a sentence talking about blue.  This sentence talks about red.';
$regex = '/.*(.{10}b' . $searchterm . 'b.{10}).*/si';
echo preg_replace($regex, '$1', $string);

输出: “ing about blue. this se”(预期)。

当我更改 $searchterm = 'red' 时,我得到以下信息:

输出: “这是一个谈论蓝色的句子。这句话谈论红色。”

我期待这个:“关于红色的lks。” 如果你从句子的开头开始,也会发生同样的事情。有没有办法使用类似的正则表达式在开始/结束时不拉回整个字符串?

正在发生的事情的例子:https : //sandbox.onlinephpfunctions.com/code/e500b505860ded429e78869f61dbf4128ff368b3

回答

将我的评论转换为答案,以便将来的访问者轻松找到解决方案。

您的正则表达式 regex 几乎是正确的,但请确保.{0,10}对周围的子字符串使用带有限制的非贪婪量词:

$searchterm = 'blue';
$string = 'Here is a sentence talking about blue.  This sentence talks about red.';
$regex = '/.*?(.{0,10}b' . $searchterm . 'b.{0,10}).*/si';
echo preg_replace($regex, '$1', $string);

更新代码演示

正则表达式演示


以上是使用preg_replace在匹配之前/之后获取字符的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>