你的lookbehind没有很好地形成。后视中的“或”条件(在 PHP 中的括号内使用时)需要相同的长度。否则,您可以像在
$str = "I'm 22 years and I have 49 years but Since 19 years and Depuis 10 ans";
preg_match_all(
'~
(?<!
\bdepuis\s |
\bsince\s |
\bmonz\s
)
\d{2}\s
(?:
ans? |
years? |
sana |
años? |
anos? |
sna
)\b
~xi',$str,$m);
print_r($m);
[编辑 2]
最后一个单词和所需部分之间可能有多个空格(如@nhahtdh在下面的评论中写道)。虽然这不是一个单一的模式,但这里是您可以避免这种情况的方法。
$pat =
'~
(
(?(?<=^)(?=\s*) # if it is the beginning of the string
(?:\s*) # match possible spaces
| # otherwise match
(?:
(?<=\s) # following a space,
(?: # a word that is not listed below
(?!(?:
depuis |
since |
monz
))
\S
)+
\s+ # and 1 or more spaces
)
)
)
\d{2}\s+ # then your pattern itself
(?:
ans? |
years? |
sana |
años? |
anos? |
sna
)\b
~xi';
preg_match_all($pat,$str,$matches);
foreach ($matches[0] as $k => &$v)
// replace the previous word if any
$v = substr($v,strlen($matches[1][$k]));
// and delete the reference
unset($v);
print_r($matches);