PHP: strip_tags - remove only certain tags (and their contents)?

前端 未结 2 847
礼貌的吻别
礼貌的吻别 2020-12-11 03:21

I use the strip_tags() function but I need to remove some tags (and all of their contents).

for example :

2条回答
  •  渐次进展
    2020-12-11 03:50

    You say that you are using Simple HTML DOM (Good! That's the right way to parse HTML). When I need to remove a tag and its contents, I do:

    $rows = $html->find("span");
    
    foreach ($rows as $row)
    {
      $row->outertext = "";
    }
    
    $html->load($html->save());
    

    The last line is required because the DOM gets confused after modifications are made so the entire DOM has to be collapsed and then parsed again so that the changes are made permanent (IMO, a bug in Simple HTML DOM).

    The Simple HTML DOM approach is safer and more stable than a regular expression.

提交回复
热议问题