用于替换和添加属性到 HTML 标签的 RegEx [英] RegEx for replacing and adding attributes to an HTML tag

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

问题描述

给定以下代码:

<body>
  <img src="source.jpg" />
  <p>
    <img src="source.jpg" id ="hello" alt="nothing" />
    <img src="source.jpg" id ="world"/>
  </p>
</body>

最好的方法是什么 - 使用正则表达式(或更好?) - 将其替换成这样:

What's the best way - using a regular expression (or better?) - to replace it so it becomes this:

<body>
  <img src="source.jpg" id="img_0" />
  <p>
    <img src="source.jpg" id ="img_1"  alt="nothing" />
    <img src="source.jpg" id ="img_2"/>
  </p>
</body>

换句话说:

  • 所有 标签都由 id 属性填充.

  • All the <image /> tags all gets populated by an id attribute.

id 属性应该包含一个递增的属性(这并不是真正的问题,因为它只是替换过程的一部分)

The id attribute should contain an incremented attribute (this is not really the problem though as its just part of the replace procedure)

我想需要两次传递,一次删除所有现有的 id 属性,另一次填充新属性?

I guess two passes are needed, one to remove all the existent id attributes and another to populate with new ones ?

推荐答案

我认为最好的方法是使用 preg_replace_callback.

I think the best approach is to use preg_replace_callback.

此外,我建议使用比目前所建议的更严格的 regexp - 如果您的页面包含一个 <img/> 标记 包含id属性?

Also I would recommend a slightly more stringent regexp than those suggested so far - what if your page contains an <img /> tag that does not contain an id attribute?

$page = '
<body>
  <img src="source.jpg" />
  <p>
    <img src="source.jpg" id ="hello" alt="nothing" />
    <img src="source.jpg" id ="world"/>
  </p>
</body>';

function my_callback($matches)
{
    static $i = 0;
    return $matches[1]."img_".$i++;
}

print preg_replace_callback('/(<img[^>]*ids*=s*")([^"]*)/', "my_callback", $page);

为我产生以下结果:

<body>
  <img src="source.jpg" />
  <p>
    <img src="source.jpg" id ="img_0" alt="nothing" />
    <img src="source.jpg" id ="img_1"/>
  </p>
</body>

regexp 有两个捕获组,第一个我们保留,第二个我们替换.我使用了很多否定字符类(例如 [^>]* = 直到关闭 >)来确保 <img/> 标签不需要具有 id 属性.

The regexp has two capturing groups, the first we preserve, the second we replace. I've used lots of negative character classes (e.g. [^>]* = up to closing >) to make sure that <img /> tags arn't required to have id attributes.

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

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