PHP搜索ID内容并添加Class


PHP search content for ID and add Class

我需要一个简单的函数,它将在wordpress内容中搜索特定的ID,然后将一个类添加到ID所在的同一元素中。

它是一个视频播放器插件,通过短代码显示自己。我的问题是插件给每个元素一个ID,如下id="video-1-player", id="video-2-player"。因此,函数需要搜索id="video-(any number)-player"的内容,然后在其中插入一个类。

谢谢!

编辑

以下是对我有效的答案。

https://stackoverflow.com/a/6180884/278629

使用DOMDocument类将文档表示为对象。查询您要查找的ID,并在其中添加一个类。从那里您可以吐出HTML。

简单示例:

// HTML to be handled (could very well be read in)
$html = "<!DOCTYPE html><html><body><p id='foo'>Foo</p></body></html>";
// Create and load our DOMDocument object
$doc = new DOMDocument();
$doc->loadHTML($html);
// Find and manipulate our paragraph
$foo = $doc->getElementById("foo");
$foo->setAttribute("class", "bar");
// Return the entire document HTML
echo $doc->saveHTML();

或者,如果您只想要受影响元素的HTML:

echo $doc->saveHTML($foo);

生成的HTML如下:

<!DOCTYPE html>
<html>
    <body>
        <p id="foo" class="bar">Foo</p>
    </body>
</html>

注意,上面的代码并没有首先检查class属性是否已经存在于元素上。您应该执行该检查,以免丢失元素上可能已经存在的任何预先存在的类。