用于HTML属性替换/添加的正则表达式 [英] Regex for HTML attribute replacement/addition

查看:104
本文介绍了用于HTML属性替换/添加的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



给定一个带有name属性的HTML标记,我想用我的代码替换它自己的属性。如果该标签缺少名称属性,我想植入我自己的属性。结果应该如下所示:

 < IMG name =img1...> => < IMG name =myImg1...> 
< IMG ...> => < IMG name =myImg1...>

这可以使用单线正则表达式吗?

。然后插入您自己的名称属性以及所有捕获的属性。

  s /< IMG 
( (?:\s +(?!name\b)\w + =[^] +)*)
(?:\s + name =[^] +)?
((?:\ s +(?! name\b)\w + =[^] +)*)
>
/< IMG name = myName$ 1 $ 2>
/ xg;


I'm looking for a single line regex which does the following:

Given a HTML tag with the "name" attribute, I want to replace it with my own attribute. If that tag lacks the name attribute, I want to implant my own attribute. The result should look like this:

<IMG name="img1" ...> => <IMG name="myImg1" ...>
<IMG ...> => <IMG name="myImg1" ...>

Can this be done with a single line regex?

解决方案

The trick is to match every complete "attribute=value" pair, but capture only the ones whose attribute name isn't "name". Then plug in your own "name" attribute along with all the captured ones.

s/<IMG
  ((?:\s+(?!name\b)\w+="[^"]+")*)
  (?:\s+name="[^"]+")?
  ((?:\s+(?!name\b)\w+="[^"]+")*)
  >
 /<IMG name="myName"$1$2>
 /xg;

这篇关于用于HTML属性替换/添加的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆