doutu6658 2018-04-10 13:51
浏览 53
已采纳

在标记中为每个表添加类名

In PHP I need to search through my $post content and find all the opening <table> tags to add a unique class name based on its index. I know the code below is wrong but hopefully gets the point across.

$content = '<table></table><p></p><table></table><p></p><table></table><p></p>';
preg_match_all('/find all <table> tags/', $content, $matches);
for ($i=0; $i < count($matches); $i++) {
    $new_value = '<table class=""' . $i . ' >'; 
    str_replace( $matches[$i], $new_value, $content);
}
  • 写回答

3条回答 默认 最新

  • duanpai9945 2018-04-10 14:56
    关注

    The better way is using a DOM parser. With Regular Expressions you are able to do this simple task without a mess but for right tool's sake, do it with a parser:

    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_use_internal_errors(false);
    $tables = $dom->getElementsByTagName('table');
    
    foreach ($tables as $i => $table) {
        $table->setAttribute('class', "table_$i");
    }
    
    echo $dom->saveHTML();
    

    Live demo

    RegEx solution, not preferred

    $counter = 0;
    echo preg_replace_callback('~<table\K>~', function() use (&$counter) {
        return ' class="table_' . $counter++ . '">';
    }, $content);
    

    Live demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部