简体   繁体   English

PHP正则表达式匹配模式匹配的最后一次出现

[英]PHP regex match last occurrences of the pattern matching

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 this. 我想做这样的事情。

Example: 例:

$string = 'hello example (a) hello example (b) (c)';
echo preg_replace('/\(.*?\)(?!.*\(.*?\))/', '', $string);

What I trying to do is to replace the last occurrences of (.*) but I failed. 我想做的是替换(。*)的最后一次出现,但是我失败了。 The output I got is hello example . 我得到的输出是hello示例 It replaces the entire first ( and the last ) which is (a) hello example (b) (c) . 它替换了整个第一个(和最后一个),这是(a)你好示例(b)(c)

My expected out put is hello example (a) hello example (b) . 我预期的输出结果是hello示例(a)hello示例(b)

Any one can give some cue? 有人可以给点提示吗? What is the correct regex to achieve what I want. 什么是实现我想要的正确正则表达式。 Thank you very much. 非常感谢你。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM