【发布时间】:2013-03-06 15:54:04
【问题描述】:
我需要一些帮助来制作一个删除两个 HTML 标记标签之间的 /> 的正则表达式。
<!-- The line could look like this -->
<td align=right valign=bottom nowrap><div>January 24, 2013 /></div></td>
<!-- Or this -->
<div>Is this system supported? /></div>
<!-- Even this -->
<span>This is a span tag /></div>
<!-- It could look like any of these but I do not want /> removed -->
<img src="example.com/example.jpg"/></img>
<img src="example.com/example.jpg"/>
<img src="example.com/example.jpg"/></img>
<div id="example"><img src="example.com/example.jpg"/></div>
(是的,我意识到 img 标签没有与之关联的结束标签。我正在动态编辑我尚未创建的无数页面;这不是我的标记。)
这是我想出的正则表达式(使用 perl):
s|(<.*?>(?!<img).*?)(\s*/>)(?!</img>)(</.*?>)|$1$3|gi;
是否有更好的正则表达式更高效或更快?
将正则表达式应用于上述示例后,结果如下:
<!-- The line could look like this -->
<td align=right valign=bottom nowrap><div>January 24, 2013></div></td>
<!-- Or this -->
<div>Is this system supported?></div>
<!-- Even this -->
<span>This is a span tag></div>
<!-- It could look like any of these but I do not want /> removed -->
<img src="example.com/example.jpg"/></img>
<img src="example.com/example.jpg"/>
<img src="example.com/example.jpg"/></img>
<div id="example"><img src="example.com/example.jpg"/></div>
【问题讨论】:
-
Regex 很少是使用 HTML 的正确答案。考虑使用 DOM 解析器。
-
我同意你的观点,但不是我正在做的事情的选择,因为我必须在后端执行此操作。
-
后端与它无关:PHP内置了一个dom解析器。(DomDocument)
-
你是对的。我说错了。我正在做一些编辑。以上只是其中之一。我不同意你的观点,DOM 解析器是要走的路,但上面的问题只是我的任务的一个更大的方面。但你对 DOM 解析器是正确的。
-
这可能使 DOM 解析器成为更好的解决方案。几乎唯一反对使用解析器来处理这种事情的好理由是,如果你只是对代码做一个小的调整,它可能会有点过头了。即使这样,它通常也是比正则表达式更好的解决方案。但是,如果您要对 HTML 代码进行大量编辑,那么使用 DOM 解析器的重要性就更大了。
标签: javascript html regex perl markup