0

I'm trying to match a certain phrase using regexp, with words boundaries, but it's not working as expected. What am I doing wrong?

if (preg_match("~\b(and you[?])\b~", " and you? ")) { echo "success"; }

Does not echo "success".

However with the word boundary excluded:

if (preg_match("~(and you[?])~", " and you? ")) { echo "success"; }

It echos "success" for some reason.

frosty
  • 2,559
  • 8
  • 37
  • 73
  • 2
    You used `\b` after `[?]`, which means after `?` there must be a word char. Maybe you need `"~\b(and you[?])~"` or `"~\b(and you[?])(?!\w)~"`? – Wiktor Stribiżew Jan 11 '17 at 13:01
  • It doesn't match because the word boundary after `you` is before `?` and there's no word (and therefore no word boundary) after that. – apokryfos Jan 11 '17 at 13:07
  • @frosty, please check the answers and my comment. It is not really clear what kind of a word boundary you are looking for. – Wiktor Stribiżew Jan 12 '17 at 07:27

2 Answers2

0

A word boundry does not match a question mark. So if you move the word boundry before the question mark, it will echo "success"

if (preg_match("~(\band you\b[?])~", " and you? ")) { echo "success"; }
Leon
  • 829
  • 6
  • 8
0

in your case it will not match as the "?" is not part of a word, therefore the last \b will not match, you can try:

if (preg_match("~(\band you[?])(?=\s|$)~", " and you? ")) { echo "success"; }

which is all instances of "and you?" followed by a space type character or end of string.

Victor Radu
  • 2,262
  • 1
  • 12
  • 18