简体   繁体   English

HTML标签内的正则表达式

[英]regex inside HTML Tag

My regex (<(div|i)\\b[^>]*>)(\\bTEST\\b)(<\\/(div|i)\\s*>) 我的正则表达式(<(div|i)\\b[^>]*>)(\\bTEST\\b)(<\\/(div|i)\\s*>)

replace = 'MOM' From replace ='MOM'从

<div clas="dfsdf">TEST</div>

is

MOM

But I want the HTML tag persists It should look like this: <div clas="dfsdf">MOM</div> 但我希望HTML标记保持<div clas="dfsdf">MOM</div>它应如下所示: <div clas="dfsdf">MOM</div>

What am I doing wrong? 我究竟做错了什么?

If you just replace with MOM , your whole match will be replaced by MOM ..In your regex <div clas="dfsdf"> is group 1 ($1), TEST is capture group 3 ($3) and </div> is group 4 ($4)... So, you have to replace it with the following 如果仅替换为MOM ,则整个匹配项将替换为MOM ..在正则表达式<div clas="dfsdf">是组1($ 1), TEST是捕获组3($ 3),而</div>是组4($ 4)...因此,您必须将其替换为以下内容

$1MOM$4

to contain what is required and replace just the capture group corresponding to TEST . 包含所需的内容,并仅替换与TEST对应的捕获组。

您可以使用环顾四周

preg_replace('~(?<=<(?:div|i)\b[^>]*>)TEST(?=</\s*(?:div|i)\s*>)~', "MOM', $str);

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

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