gpt4 book ai didi

php - 在 PHP 中查找字符串中的模式的正则表达式

转载 作者:行者123 更新时间:2023-12-03 23:06:14 25 4
gpt4 key购买 nike

假设我有一个如下所示的字符串:

"lets refer to [[merp] [that entry called merp]] and maybe also to that entry called [[blue] [blue]]"

这里的想法是替换一个 block [[name][some text]]<a href="name.html">some text</a> .

所以我尝试使用正则表达式来查找看起来像 [[name][some text]] 的 block ,但我遇到了巨大的困难。

这是我认为应该起作用的(在 PHP 中): preg_match_all('/\[\[.*\]\[.*\]/', $my_big_string, $matches)

但这只会返回一个匹配项,即来自 '[[merp' 的字符串至 'blue]]' .我怎样才能让它返回两个匹配 [[merp][that entry called merp]][[blue][blue]]

最佳答案

您要查找的正则表达式是 \[\[(.+?)\]\s\[(.+?)\]\]并将其替换为 <a href="$1">$2</a>

() 中匹配的正则表达式模式大括号被捕获并可以使用 $1, $2,... 进行反向引用

关于 regex101.com 的示例

关于php - 在 PHP 中查找字符串中的模式的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22891135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com