单词边界 preg_replace

word boundaries preg_replace

我想捕获与 %[a-z0-9] 匹配的任何字符串,参考以下示例:

1. %xxxxxxxxxxxxx                                 //match
2. this will work %xxxxxx but not this%xxxxxxxxx. //match 1st, not 2nd
3. and also %xxxxxxxxxx.                          //match
4. just a line ending with %xxxxxxxxxxx           //match
5. %Xxxxxxxxxxx                                   //no match
6. 100% of dogs                                   //no match
7. 65%. Begining of new phrase                    //no match
8. 65%.Begining of new phrase                     //no match

它可以在字符串的开头或结尾,但不能在单词的中间。它当然可以作为一个单词出现在字符串中(以space分隔)。

我试过了

/(\b)%[a-z0-9]+(\b)/
/(^|\b)%[a-z0-9]+($|\b)/
/(\w)%[a-z0-9]+(\w)/

和其他人一样,但我无法让它像我想的那样工作。我猜 \b 标记在示例 2 中不起作用,因为在 % 符号之前有一个边界。

如有任何帮助,我们将不胜感激。

尝试

/\B%[a-z0-9]+\b/

space 和 % 之间没有 word boundary \b,但是 s 和 [=12] 之间有一个 word boundary \b =].

\B\b相反,不是词界。

regex101

上查看
%[a-z0-9]+(?=\s|$)|(?:^|(?<=\s))%[a-z0-9]+

尝试 this.See 演示。

https://regex101.com/r/iS6jF6/20

$re = "/%[a-z0-9]+(?=\s|$)|(?:^|(?<=\s))%[a-z0-9]+/m";
$str = "1. %xxxxxxxxxxxxx //match\n2. this will work %xxxxxx but not this%xxxxxxxxx. //match 1st, not 2nd\n3. and also %xxxxxxxxxx. //match\n4. just a line ending with %xxxxxxxxxxx //match\n5. %Xxxxxxxxxxx //no match\n6. 100% of dogs //no match\n7. 65%. Begining of new phrase //no match\n8. 65%.Begining of new phrase //no match";

preg_match_all($re, $str, $matches);

%[a-z0-9]+\b|\b%[a-z0-9]+