PHP regex match last occurrences of the pattern matching

前端 未结 2 600
爱一瞬间的悲伤
爱一瞬间的悲伤 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);
    
    0 讨论(0)
  • 2021-01-27 06:40

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

    0 讨论(0)
提交回复
热议问题