开发者

PHP search content for ID and add Class

开发者 https://www.devze.com 2023-03-12 04:34 出处:网络
I need a simple function that will search my wordpress content for a specific ID, and than add a class to the same element the ID is in.

I need a simple function that will search my wordpress content for a specific ID, and than add a class to the same element the ID is in.

Its for a开发者_StackOverflow中文版 video player plugin that displays itself via shortcode. My problem is the plugin gives each element an ID as follows, id="video-1-player", id="video-2-player". So the function needs to search the content for id="video-(any number)-player" and than insert a class in there.

thanks!

EDIT

heres the answer that worked for me.

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


Use the DOMDocument class to represent your document as an object. Query for the ID you're seeking, and add a class onto it. From there you can spit the HTML back out.

Simple example:

// 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();

Alternatively, if you only wanted the HTML for the affected element:

echo $doc->saveHTML($foo);

The generated HTML follows:

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

Note that the above code doesn't first check to see if the class attribute is already present on the element. You should perform that check so as to not lose any pre-existing classes that might already be on the element.

0

精彩评论

暂无评论...
验证码 换一张
取 消