正则表达式从HTML中提取文本

Ron*_*lev 17 html regex text-extraction html-content-extraction

我想从一般HTML页面中提取所有文本(显示与否).

我想删除

  • 任何HTML标签
  • 任何javascript
  • 任何CSS样式

是否有正则表达式(一个或多个)将实现这一目标?

nic*_*ckf 16

删除javascript和CSS:

<(script|style).*?</\1>
Run Code Online (Sandbox Code Playgroud)

删除标签

<.*?>
Run Code Online (Sandbox Code Playgroud)

  • /<(.|\n)*?>/g将带您到天堂之城. (8认同)

S.L*_*ott 11

您无法使用正则表达式真正解析HTML.这太复杂了.RE根本不会<![CDATA[正确处理部分.此外,某些常见的HTML内容&lt;text>会在浏览器中作为正确的文本工作,但可能会让一个天真的RE感到困惑.

使用正确的HTML解析器,您会更快乐,更成功.Python人经常使用Beautiful Soup来解析HTML并删除标签和脚本.


此外,浏览器在设计上容忍格式错误的HTML.因此,您经常会发现自己试图解析明显不合适的HTML,但在浏览器中运行正常.

您可以使用RE解析错误的HTML.它需要的只是耐心和努力.但是使用别人的解析器通常更简单.

  • @monoxide:我的观点并非不可能.我的观点是,你可以通过使用其他正确处理所有边缘情况的解析器来节省大量RE的调试. (3认同)

Joe*_*vin 6

需要一个正则表达式解决方案(在PHP中),它将返回纯文本(或更好)PHPSimpleDOM,只是更快.这是我提出的解决方案:

function plaintext($html)
{
    // remove comments and any content found in the the comment area (strip_tags only removes the actual tags).
    $plaintext = preg_replace('#<!--.*?-->#s', '', $html);

    // put a space between list items (strip_tags just removes the tags).
    $plaintext = preg_replace('#</li>#', ' </li>', $plaintext);

    // remove all script and style tags
    $plaintext = preg_replace('#<(script|style)\b[^>]*>(.*?)</(script|style)>#is', "", $plaintext);

    // remove br tags (missed by strip_tags)
    $plaintext = preg_replace("#<br[^>]*?>#", " ", $plaintext);

    // remove all remaining html
    $plaintext = strip_tags($plaintext);

    return $plaintext;
}
Run Code Online (Sandbox Code Playgroud)

当我在一些复杂的网站上测试这个(论坛似乎包含一些更难解析的html)时,这个方法返回与PHPSimpleDOM明文相同的结果,只是更快,更快.它还正确处理了列表项(li标签),而PHPSimpleDOM没有.

至于速度:

  • SimpleDom:0.03248秒.
  • RegEx:0.00087秒.

快37倍!