整个单词和部分单词的匹配

问题描述 投票:0回答:3

我的代码是:

$tt = 'This is a tomato test';
preg_match('/is(.*)to/', $tt, $match);
print_r($match); 

从此我试图仅获得

" a toma"
输出......但它给了我:

Array
(
    [0] => is is a tomato
    [1] =>  is a toma
)

为此,正则表达式如何使其不在输出字符串开头显示额外的“is”(

this
的尾随字母)?

php regex regex-greedy word-boundaries
3个回答
1
投票

最简单的解决方案是注意“this”包含子字符串“is”,所以...

$tt='This is a tomato test';
$rr=preg_match('/ is(.*)to/',$tt,$match); // add a space before is.
print_r($match); 

并且

[1]
将是“a toma”


1
投票

另一个技巧是使用后向断言

(?<=
,其内容不会成为结果匹配的一部分:

preg_match('/(?<=\bis)(.*)to/', $tt, $match);

0
投票

您需要的称为后视,如下所述http://www.regular-expressions.info/lookaround.html

具体来说你想要类似

'/(?<= is)(.*)to/'

的东西
© www.soinside.com 2019 - 2024. All rights reserved.