While using regex is typically less performant than non-regex techniques, I do appreciate the control and flexibility that it affords.
In my snippet, I will set the pattern to be case-insensitive (\i
, although my sample input will not challenge this rule) and include word boundaries (\b
, although they were not explicitly called for).
I am also going to use the \K
metacharacter to reset the fullstring match so that no capture groups / backreferences are needed.
Code: (Demo)
$search = 'The';
$replace = 'A';
$subject = "The Quick Brown Fox Jumps Over The Lazy Dog's Thermos!";
echo preg_replace(
'/.*\K\b' . preg_quote($search, '/') . '\b/i',
$replace,
$subject
);
Output:
The Quick Brown Fox Jumps Over A Lazy Dog's Thermos!
# ^^^ ^ ^^^
# not replaced replaced not replaced
Without word boundaries: (Demo)
echo preg_replace(
'/.*\K' . preg_quote($search, '/') . '/i',
$replace,
$subject
);
Output:
The Quick Brown Fox Jumps Over The Lazy Dog's Armos!
# ^^^ ^^^ ^
# not replaced not replaced replaced