【问题标题】:How to replace multiple span tags with same class name with a single span tag using PHP Regular Expression如何使用 PHP 正则表达式将具有相同类名的多个跨度标签替换为单个跨度标签
【发布时间】:2017-04-26 11:54:34
【问题描述】:

我必须使用 PHP 正则表达式将所有具有相同类名的 span 标签替换为单个 span 标签。我知道我们可以通过使用 DOMDocument 以及使用 javascript/jQuery 来做到这一点。我也尝试使用下面的代码,但它关闭了。

[<span(.*)><strong>*](.*)<\/strong><\/span>

下面是我所指的代码。

<span class="c28"><strong><span class=
  "c28"><strong><span class="c28"><strong><span class=
  "c28"><strong><span class="c28"><strong><span class=
  "c28"><strong><span class="c28"><strong><span class=
  "c28"><strong><span class="c28"><strong><span class=
  "c28"><strong><span class="c28"><strong><span class=
  "c28"><strong><span class="c28"><strong><span class=
  "c28"><strong><span class="c28"><strong><span class=
  "c28"><strong><span class="c28"><strong><span class=
  "c28"><strong><span class="c28"><strong><span class=
  "c28"><strong>Sending text messages that include links,
  attachments and/or
  pictures.</strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span></strong></span>

我想要这样的输出

<span class="c28"><strong>Sending text messages that include links, attachments and/or pictures.</strong></span>

谁能帮我解决这个正则表达式。谢谢

【问题讨论】:

  • @ 987654321@为什么为什么ṫ̨̗̺̭̮̞̗̜̮̗̙̫̺̖̭̯͊ͨ̌͒̍͘͘͟͝h̸͓̩̙͙̻̗͔̞̘̟̩̯͋͑͂͐a̴̧ͨ́ͭ͒ͯ̓͐ ̃ͥ͢҉‌ ̃ͥ͢҉‌ t̵̳̳͕͉͋̓͐ͦͬ̈́̀̚‌是个坏主意
  • 获得内部的&lt;strong&gt; 并放置&lt;span&gt; 怎么样?
  • 看来这不仅仅是span 标签,因为strongs 也会在您想要的输出中自动删除。
  • 我觉得比这里使用DOM更理想。这并不总是一个坏主意。 @ThomasAyoub
  • [&lt;span(.*)&gt;&lt;strong&gt;*] 不是在寻找 spanstrong 元素,您正在寻找其中列出的一个字符。如果格式一致(只有跨度和字符串重复),您可以使用strpos 搜索&lt;span class="c28"&gt;&lt;strong&gt;,如果您有它剥离所有标签,然后在前面加上&lt;span class="c28"&gt;&lt;strong&gt; 并附加结束。

标签: php regex preg-replace


【解决方案1】:

应避免嵌套strongs。还嵌套了spans,不管它们的类名是什么,它紧随其后的另一个演示了滥用HTML 实现。你可以选择:

(</?\w+[^>]*>)(?1)*\1

Live demo

PHP 代码:

preg_replace('~(</?\w+[^>]*>)(?1)*\1~', '\\1', $string);

【讨论】:

    【解决方案2】:

    在这种情况下,您可以利用 非空 &lt;strong&gt;文本内容这一事实 - 这意味着您可以公平地使用它简单模式:

    正则表达式:.*?class="(\w+)".*(&lt;strong&gt;[^&lt;]+&lt;\/strong&gt;).*

    替换:&lt;span class="$1"&gt;$2&lt;/span&gt;

    https://regex101.com/r/mtUBWx/2/

    【讨论】:

    • 感谢您的解决方案。该解决方案仅在类名相同(c28)时才有效,但对我们而言,此处进行的替换类名不同。
    • 我已经修改了正则表达式和替换字符串以动态获取类名,并更新了链接。
    猜你喜欢
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2023-02-09
    • 2014-07-24
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2021-02-20
    相关资源
    最近更新 更多