PHP 从抓取的 HTML 中删除 HTML 代码,带出 id/class



我需要从我正在抓取的 html 中删除此 html 代码,但我无法使用其 id 或类来定位它。我需要删除 html 代码上的所有实例。

<ul data-bfa="@l:Subbuzz-Share;">
    <!-- MORE CODES -- >
</ul>
您可以使用

str_replace或正则表达式(正则表达式(来执行此操作

对于这个特定的元素,让我们使用str_replace:

// let's variable that contains the html tag
$html = '
   <ul data-bfa="@l:Subbuzz-Share;">
    <!-- MORE CODES -- >
  </ul>
';
$html = str_replace('data-bfa="@l:Subbuzz-Share;"','',$html);

查看更多: http://tr2.php.net/manual/tr/function.str-replace.php

让我们使用正则表达式,您可以在一生中的许多情况下使用它

// let's variable that contains the html tag
$html = '
   <ul data-bfa="@l:Subbuzz-Share;">
    <!-- MORE CODES -- >
  </ul>
';
$html = preg_replace('data-bfa=".+"','',$html);
// or another way with regex
$html = preg_replace('data-.+=".+"','',$html);

查看更多: http://tr2.php.net/manual/tr/function.preg-replace.php还要检查 tis 站点,它非常有用,可以尝试正则表达式:http://regexr.com/

编辑:更具体

要限制 html 标记类型,请执行以下操作:

// this is for str_replace but not good idea for this kind of situations, and it may not work if it doesn't match exactly
$html = str_replace('<ul data-bfa="@l:Subbuzz-Share;">','<ul>',$html);
// this for preg_replace
$html = preg_replace('(<ul )data-.+=".+"','$1',$html);
// this for preg_replace as well
$html = preg_replace('(<ul .+) data-.+=".+"','$1',$html);

您可能会感到困惑,为了理解正则表达式,您需要做的是研究正则表达式:)

最新更新