I was trying to use this but unable to understand what is wrong here
preg_match('/\b'.$string.'\b/i', $fullstring);
The intention is to match a whole word only where the word is someone's input which will be part of variable $string
. E.g., "my name is alto better" which is separated by ' | ' to act as OR in regex operation.
<?php
$fullstring = 'Palo Alto New york colombia europe today Tomorrrow';
$string = 'my|name|is|alto|better';
preg_match('/\b'.preg_quote($string).'\b/i', $fullstring, $match);
print_r($match);
Output is null. What could be wrong?
If your input is a regular expression with alternative branches you need to apply the word boundaries to a group, see
preg_match('/\b(?:' . $string . ')\b/i', $fullstring, $match);
Why use a grouping construct? Because if you just add word boundaries to the 'my|name|is|alto|better'
regex pattern, only my
and better
will be restricted in part: my
will only match at the beginning of a word and better
will match at the end of a word - that is in short the essence of the issue you had after adding word boundaries without grouping the alternatives first.