dlofrodloh dlofrodloh - 5 months ago 7
PHP Question

Regex replace a string in a string when it's not followed or preceded alphanumeric chars

I've got the test string:

$string="or(or apple and orange) or banana"


I want to replace any instance of
or
in the string when it's not part of another word, e.g.
orange
and just make it uppercase and ensure there's spaces on either side of it.

So the above string should become:
OR ( OR apple and orange) OR banana


I'm not terribly good at regex, and I've tried:

$string = preg_replace('([^a-zA-Z]or[^a-zA-Z])', ' OR ', $string);


Which gives me:
or OR apple and orange) OR banana


And that is quite far off. What would be correct regex to achive the desired output?:

Answer

Use word boundary(\b)

$string = preg_replace("/\bor\b/", 'OR', $string);
Comments