【问题标题】:Deleting elements with PHP that contains specific id or classes attribute使用 PHP 删除包含特定 id 或 classes 属性的元素
【发布时间】:2015-02-11 16:54:50
【问题描述】:

我有一个简单的问题,但没有找到答案。

我有这个简单的 html 代码:

<div class="iWantThisElement">
Not Delete this one
</div>
...
<div class="itemx">
Delete This
</div>
...
<span id="xxitemsxx">
Delete This
</span>
...
<div class="delete">
Delete This
</div>
...
<h2 id="deleteThisOneToo">
Delete This
</h2>
...
<div class="Iwantthis">
Not Delete this one
</div>

我想有一个规则来删除它们的 class 或 id 包含特定单词或单词的所有元素,例如,我想删除类或带有这些词的 ID:

itemx,xxitemsxx,deleteThisOneToo,delete

所以,我们可以有一个这样的数组:

$array = array("item","delete");

如果 any 元素(如 h2、div、span 等)包含该 id 或 class数组,必须删除。

该 html 的输出必须是这样的:

<div class="iWantThisElement">
Not Delete this one
</div>
...
...
...
...
...
<div class="Iwantthis">
Not Delete this one
</div>

我已经尝试了很多带有 preg_replace 和模式的代码,但我无法解决它。

我们如何在 php 中做到这一点?用最好最快的方法?

谢谢。

【问题讨论】:

  • 您最好使用 Javascript 来执行此操作。 PHP 是服务器端的,它并不是真的适合这种东西,它是可行的,但它不会很漂亮。
  • @AndreiP。我知道我可以做到,但我需要在服务器端做到这一点。
  • 好吧,我和下一个人一样喜欢一些肮脏的工作。添加一些真实的代码,我们会谈谈。

标签: php arrays regex preg-replace


【解决方案1】:

在div类中搜索this:

/&lt;[^&lt;]+class=[^&gt;]+this[^&gt;]+&gt;[^&lt;]+&lt;\/div&gt;/img

在div id 中搜索this:

/&lt;[^&lt;]+id=[^&gt;]+this[^&gt;]+&gt;[^&lt;]+&lt;\/div&gt;/img

最后是类、id 和任何标签的示例:

$source = "<div..."; // your html markup
$find_word = "this";
$class_pattern = array("/<[^<]+class=[^>]+", "[^>]+>[^<]+<\/[a-z]+>/i");
$id_pattern = array("/<[^<]+id=[^>]+", "[^>]+>[^<]+<\/[a-z]+>/i");
$result = preg_replace($class_pattern[0].$find_word.$class_pattern[1], "", $source);
$result = preg_replace($id_pattern[0].$find_word.$id_pattern[1], "", $result);

演示: http://sandbox.onlinephpfunctions.com/code/2f64fae1d6cbaa0efc7e777e653097891a43113d

【讨论】:

  • 谢谢亲爱的,但它不起作用,我在最后一行,first_word 之后的代码可能是这样的? $class_pattern[1],不是[0]
  • 哦,是的!这只是错字。
  • Tnx 再次,但问题是,如果现在我们将 this 更改为 item span id 不会被删除。你也可以修这个吗?
  • 再次感谢亲爱的鲁本,你能检查一下吗? sandbox.onlinephpfunctions.com/code/…这段代码有什么问题?
  • 代码没问题。你的问题是关于&lt;tag attr="value"&gt;content&lt;/tag&gt;。现在模板是&lt;tag attr="value"&gt;&lt;tag ...。这是绝对不同的故事。如果要删除折叠闭包,则应计算父子关系并删除 HTML 树的整个分支。你需要解析器。您应该在回显之前将整个 html 端清理干净。此活动已结束您的问题。对不起。好消息,您可以在 html 内容加载后使用 jQuery 轻松完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 2021-11-13
  • 2019-11-05
  • 2015-03-03
  • 2018-02-28
相关资源
最近更新 更多