使用 DOMDocument 将新类添加到 div

它工作正常,但我有两个小问题:

  1. 如果我在 IMG 中已经有一个类 - 当前的 php 代码会删除前一个类,只添加一个新类 (picla)。我希望它们都可用(旧类和 picla)。

  2. 我希望仅当图像具有“alt”属性时才添加 .picla 类。如果没有,请不要添加 .picla 类。

我怎样才能做到呢?

请帮我。

例如在字符串中我有:

<img alt="Description 2" src="1.jpg" style="height:560px; width:840px" class="dupa" data-label-class="label-class">

在我的 php 脚本之后我有:

<img alt="Description 2" src="1.jpg" style="height:560px; width:840px" class="picla" data-label-class="label-class"> .

正确的结果是:

<img alt="Description 2" src="1.jpg" style="height:560px; width:840px" class="dupa picla" data-label-class="label-class">

(2级)


拉风的咖菲猫
浏览 37回答 1
1回答

绝地无双

添加所需的检查alt和class属性:foreach ($tags as $tag) {&nbsp; &nbsp; // get value of an `alt` attribute&nbsp; &nbsp; $alt = $tag->getAttribute('alt');&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (!empty($alt)) {&nbsp; &nbsp; &nbsp; &nbsp; // get current class(es)&nbsp; &nbsp; &nbsp; &nbsp; $class = $tag->getAttribute('class');&nbsp; &nbsp; &nbsp; &nbsp; if (!empty($class)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $class .= " picla";&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $class = "picla";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $tag->setAttribute('class', $class);&nbsp; &nbsp; }&nbsp; &nbsp; // other code here}这里简单的小提琴。
打开App,查看更多内容
随时随地看视频慕课网APP