更新时间:2022-11-11 21:55:26
问题是您只获得包含\b
-单词边界的匹配项.由于星号是非单词字符,因此将其从匹配项中删除,因此解决方案是允许单词边界或星号(\*|\b)
:
The problem was that you were only getting matches that include a \b
- a word boundary. Since an asterisk is a non-word character, it was eliminating it from the match, so the solution was to allow for either a word boundary or an asterisk (\*|\b)
:
preg_replace('/([a-z0-9.]+)((\*|\b)(?<!or|and|not))/i', '$0'."[45]", $term);
但是,使用负前瞻进行操作会更简单:
However, it's simpler to do it with a negative lookahead:
preg_replace('/\b(?!or|and|not)([a-z0-9*.]+)/i', '$0'."[45]", $term);
注意:在字符类中,星号和点号不是元字符,因此不需要像原始表达式中那样转义它们:[a-z0-9\*\.]+
.
Note: Within character classes asterisks and periods are not metacharacters, so they don't need to be escaped as you had in your original expression: [a-z0-9\*\.]+
.