PHP regex match last occurrences of the pattern matching

前端 未结 2 599
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 06:28

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

2条回答
  •  隐瞒了意图╮
    2021-01-27 06:32

    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);
    

提交回复
热议问题