文本 = 123123<span class="type2">123123</span>123<a href="/123" title="123">123123</a>123 结果 = 1[2]31[2]3<span class="type2">1[2]31[2]3</span>1[2]3<a href="/123" title="123">1[2]31[2]3</a>1[2]3
即在 html 标签中的不可以被替换,非 html 标签的则替换为[\1]即可,PHP 的 preg_replace ,不过正则应该通用的
V2EX 用户提问: https://www.v2ex.com/t/843965
#regex #正则表达式 #html-tag
下面是 JS 的正则
str.replace(/((<[^>]+>)*[^<>]*?)(关键字)/gim, "$1[$3]")
下面是 PHP 的正则
preg_replace("/((<[^>]+>)*[^<>]*?)(关键字)/im", "$1[$3]", $str);