php - 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?
解决方案
我不知道你想匹配什么.*
。你不需要它。这将正常工作:
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" 在双引号内。
推荐阅读
- string - 如何从字符串中删除所有其他逗号
- neo4j - 如何将对象数组转换为带有键的对象?
- javascript - JSON 对象仅显示第一个键,忽略其余键
- java - 元素 xsl:mode 不得直接出现在 xsl:stylesheet 中
- timber - tax_query 在 Timber 的 Twig 文件中不起作用
- python - Python,从网站中提取 XHR 响应数据
- javascript - module.exports 对象传播间歇性地工作
- php - PHP 有 FIPS 模式吗?它是否提供选择 FIPS 或非 FIPS 的选项/标志?
- gdb - 如何使用 GDB 查找 Android 目标处理器的基地址
- java - 信号是否保证到达线程?