duan117890 2011-06-10 12:21
浏览 54
已采纳

PHP搜索ID的内容并添加Class

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 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

  • 写回答

1条回答 默认 最新

  • dongzhuo5425 2012-11-18 05:28
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法