单词边界preg_replace

时间:2015-03-12 11:13:40

标签: php regex word-boundary

我想抓住任何匹配%[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

它可以在字符串的开头或结尾处,但不是在单词的中间。它当然可以在字符串中作为单词(由空格分隔)。

我试过了

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

和其他人一样,但我不能像我一样工作。我想\ b令牌在示例2中不起作用,因为在%符号之前有一个边界。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

尝试

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

您在空格与\b之间没有word boundary %,但s%之间有一个。{/ p >

\B\b相反,而不是单词边界。

regex101

上查看

答案 1 :(得分:0)

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

试试这个。看看演示。

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]+