I know there is a negative lookahead regex that can match last occurrences of the string.
Example: replace last occurrences of string
I want to do something like
You want to use a negated character class here instead of .*?
.
The .*
inside of your lookahead assertion will match all the way up to the last occurrence of (...)
then backtrack consecutively keeping the succession order going.
preg_replace('/\([^)]*\)(?!.*\([^)]*\))/', '', $string);
To simplify this task, just retain everything up until the last occurrence instead.
preg_replace('/.*\K\(.*?\)/', '', $string);
Youre mistake is using \(.*\)
it's replace full substring which begins whith (
and ends whith )
. .*
- max quantificator, (.*)
- min quantificator.
Try to use:
$string = 'hello example (a) hello example (b) (c)';
echo preg_replace('/\((.*)\)$/', '', $string);