Regex match exact words

Fjott picture Fjott · Jul 18, 2017 · Viewed 8.6k times · Source

I want my regex to match ?ver and ?v, but not ?version

This is what I have so far: $parts = preg_split( "(\b\?ver\b|\b\?v\b)", $src );

I think the trouble might be how I escape the ?.

Answer

Wiktor Stribiżew picture Wiktor Stribiżew · Jul 18, 2017

Your pattern tries to match a ? that is preceded with a word char, and since there is none, you do not have a match.

Use the following pattern:

'/\?v(?:er)?\b/'

See the regex demo

Pattern details:

  • \? - a literal ? char
  • v(?:er)? - v or ver
  • \b - a word boundary (i.e. there must be a non-word char (not a digit, letter or _) or end of string after v or ver).

Note you do not need the first (initial) word boundary as it is already there, between a ? (a non-word char) and v (a word char). You would need a word boundary there if the ? were optional.