简体   繁体   English

如何使用PHP正则表达式用单个span标签替换具有相同类名的多个span标签

[英]How to replace multiple span tags with same class name with a single span tag using PHP Regular Expression

I have to replace all the span tags with the same class name to a single span tag using PHP regular expression. 我必须使用PHP正则表达式将具有相同类名的所有span标记替换为单个span标记。 I got to know we can do this by using DOMDocument and also by using javascript/jQuery. 我知道我们可以通过使用DOMDocument和javascript / jQuery来做到这一点。 Also i tried with the code below but its close. 我也尝试了下面的代码,但它关闭了。

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

Below is the code I'm referring to. 下面是我要引用的代码。

<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>

I want the output like 我想要像这样的输出

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

Can anyone please help me with this regular expression. 任何人都可以用这个正则表达式来帮助我。 Thanks 谢谢

In this case, you could make use of the fact that you are targeting a non-empty <strong> with text content - which means you can use this fairly simple pattern: 在这种情况下,您可以利用针对文本内容非空 <strong>的事实-这意味着您可以使用以下非常简单的模式:

regex: .*?class="(\\w+)".*(<strong>[^<]+<\\/strong>).* 正则表达式: .*?class="(\\w+)".*(<strong>[^<]+<\\/strong>).*

replace: <span class="$1">$2</span> 替换: <span class="$1">$2</span>

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

Nested strong s should be avoided. 应避免嵌套的strong Also nested span s, regardless of their class names, which immediately come after the another demonstrate a misuse of HTML implementation. 嵌套的span ,无论它们的类名如何,紧随其后的嵌套span都表明滥用HTML实现。 You may go with: 您可以选择:

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

Live demo 现场演示

PHP code: PHP代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM