PHP: preg_match regex cannot find the correct lines

preg_match_all('/[\s]{1}(AA|BB|CC)+[\s]{1}/',' AA BB ',$matches); 

result is AA , but I need AA and BB .

+6
php regex
source share
3 answers

The sequences [\s]{1} * that you use to match spaces between matches. The final space after "AA " is the same space as before " BB" . Any one character can be matched only once, therefore, after detecting an " AA " scan " AA " it searches only the remaining "BB " string for matching and cannot find it.

Try the escape sequence of the words \b . This corresponds to the beginning and end of words, but does not actually consume any characters, so it can match several times:

 preg_match_all('/\b(AA|BB|CC)+\b/', 'AA BB', $matches); 

Using \b has a bonus effect that does not require the extra spaces that you surrounded your string. You can simply pass 'AA BB' instead of ' AA BB ' if you want.

* By the way, [\s]{1} is the same as [\s] , which matches the simple \s . No need for square or curly brackets.

+2
source share

The problem is that you are trying to map the same space twice. Using appearance (? = \ S) should help:

 preg_match_all('/\s(AA|BB|CC)(?=\s)/',' AA BB CC BB AA ',$matches); 
0
source share

You can make a positive appearance:

/(?<=\s)(AA|BB|CC)+\s/


Resources:

0
source share

All Articles