dongxin5054 2012-05-06 16:16
浏览 60
已采纳

正则表达式匹配HTML标记内的文本

I'm trying to write a regex that will remove HTML tags around a placeholder text, so that this:

<p>
    Blah</p>
<p>
    {{{body}}}</p>
<p>
    Blah</p>

Becomes this:

<p>
    Blah</p>
{{{body}}}
<p>
    Blah</p>

My current regex is /<.+>.*\{\{\{body\}\}\}<\/.+>/msU. However, it will also remove the contents of the tag preceding the placeholder, resulting in:

{{{body}}}
<p>
    Blah</p>

I can't assume the users will always place the placeholder inside <p>, so I would like it to remove any pair of tags immediately around the placeholder. I would appreciate some help with correcting my regex.

[EDIT]

I think it's important to note that the input may or may not be processed by CKEditor. It adds newlines and tabs to the opening tags, thus the regex needs to go with the /sm (dotall + multiline) modifiers.

  • 写回答

2条回答 默认 最新

  • douliedai4838 2012-05-06 16:20
    关注

    Try this:

    <[^>]+>\s*\{{3}body\}{3}\s*<\/[^>]+>
    

    See it here in action: http://regexr.com?30s4o

    Here's the breakdown:

    • <[^>]+> matches an opening HTML tag, and only that.
    • \s* captures any whitespace (equivalent to [ \t ]*)
    • \{{3} matches a { exactly 3 times
    • body matches the string literally
    • \}{3} matches a } exactly 3 times
    • \s* again, captures any whitespace
    • <\/[^>]+> matches a closing HTML tag
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答