doutu6658 2018-04-10 21: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 22: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条)

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行