首页 > 解决方案 > preg_replace on the actual match ( index 1) instead of whole string

问题描述

Consider

preg_replace('/(lets go).*/', "going", "lets go somewhere")

It will output: "going", I want "going somewhere".

preg_replace seems to replace using the first match which is the whole string "lets go somewhere". How can I make it ignore index 0 and only target index 1?

标签: phpregexpreg-replace

解决方案


我不知道你想匹配什么.*。你不需要它。这将正常工作:

preg_replace('/(lets go)/', "going", "lets go somewhere");

或者您可以使用惰性匹配:

preg_replace('/(lets go).*?/', "going", "lets go somewhere");

解释:你原来的表情是贪婪的。这大致意味着.*匹配尽可能多的字符。.*?懒惰;它匹配最少数量的字符。

您还可以匹配“某处”作为子模式,并在替换中使用它:

preg_replace('/(lets go)(.*)/', "going\$2", "lets go somewhere");

这里。$0 是“让我们去某个地方”,$1 是“让我们去”,$2 是“某个地方”。需要反斜杠,因为 "going\$2" 在双引号内。


推荐阅读