在PHP中,如何从html标签中删除特定的类? [英] in PHP, how to remove specific class from html tag?

查看:110
本文介绍了在PHP中,如何从html标签中删除特定的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中给出以下字符串:

  $ html =< div> 
< p> < span class ='test1 test2 test3'> text 1< / span>< / p>
< p>< span class ='test1 test2'> text 2< / span>< / p>
< p>< span class ='test1'> text 3< / span>< / p>
< p>< span class ='test1 test3 test2' > text 4< / span>< / p>
< / div>;

我只想将任何具有test2的类清空或删除,结果将是这样的:

 < div> 
< p>< span class =''> text 1< / span>< / p>
< p>< span class =''> text 2< / span>< / p>
< p>< span class ='test1'> text 3< / span>< / p>
< p>< span class =''> text 4< / span>< / p>
< / div>

如果您删除元素:

 < DIV> 
< p>文字1< / p>
< p> text 2< / p>
< p>< span class ='test1'> text 3< / span>< / p>
< p>文本4< / p>
< / div>

我很乐意使用正则表达式或类似PHP Simple HTML DOM Parser的内容,但我有没有线索如何使用它。并且使用正则表达式,我知道如何找到元素,而不是与它相关联的特定属性,特别是如果有多个属性,像我上面的例子。任何想法?

解决方案

  $ notest2 = preg_replace(
/ class \\ s * = \s *'[^ \'] * test2 [^ \'] *'/,
class ='',
$ src)

C。


given the following string in PHP:

$html = "<div>
<p><span class='test1 test2 test3'>text 1</span></p>
<p><span class='test1 test2'>text 2</span></p>
<p><span class='test1'>text 3</span></p>
<p><span class='test1 test3 test2'>text 4</span></p>
</div>";

I just want to either empty or remove any class that has "test2" in it, so the result would be this:

<div>
<p><span class=''>text 1</span></p>
<p><span class=''>text 2</span></p>
<p><span class='test1'>text 3</span></p>
<p><span class=''>text 4</span></p>
</div>

of if you're removing the element:

<div>
<p>text 1</p>
<p>text 2</p>
<p><span class='test1'>text 3</span></p>
<p>text 4</p>
</div>

I'm happy to use a regex expression or something like PHP Simple HTML DOM Parser, but I have no clue how to use it. And with regex, I know how to find the element, but not the specific attribute associated w/ it, especially if there are multiple attributes like my example above. Any ideas?

解决方案

$notest2 = preg_replace(
         "/class\s*=\s*'[^\']*test2[^\']*'/", 
         "class=''", 
         $src);

C.

这篇关于在PHP中,如何从html标签中删除特定的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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