【问题标题】:How to extract only text from HTML string with PHP?如何使用 PHP 从 HTML 字符串中仅提取文本?
【发布时间】:2014-12-08 05:36:17
【问题描述】:

我只想从 php 字符串中提取文本。

这个 php 字符串包含 html 代码,如标签等。

所以我只需要这个字符串中的一个简单文本。

这是实际的字符串:

<div class="devblog-index-content battlelog-wordpress">
<p><strong>The celebration of the Recon class in our second </strong><a href="http://blogs.battlefield.com/2014/10/bf4-class-week-recon/" target="_blank">BF4 Class Week</a><strong> continues with a sneaky stroll down memory lane. Learn more about how the Recon has changed in appearance, name and weaponry over the years&hellip;</strong></p>

<p>&nbsp;</p>

<p style="text-align:center"><a href="http://eaassets-a.akamaihd.net/battlelog/prod/954660ddbe53df808c23a0ba948e7971/en_US/blog/wp-content/uploads/2014/10/bf4-history-of-recon-1.jpg?v=1412871863.37"><img alt="bf4-history-of-recon-1" class="aligncenter" src="http://eaassets-a.akamaihd.net/battlelog/prod/954660ddbe53df808c23a0ba948e7971/en_US/blog/wp-content/uploads/2014/10/bf4-history-of-recon-1.jpg?v=1412871863.37" style="width:619px" /></a></p>

我想从字符串中显示这个:

The celebration of the Recon class in our second BF4 Class Week continues with a sneaky stroll down memory lane. Learn more about how the Recon has changed in appearance, name and weaponry over the years…

实际上这个文本将被放置在元描述标签中,所以我不需要在元标签中添加任何 HTML。 我该怎么做?关于这项技术的任何想法和想法?

【问题讨论】:

  • 用strip_tags()删除所有html标签
  • 使用 strip_tags(),查看手册,您将获得有关如何使用它以及它的作用的详细信息。

标签: php


【解决方案1】:

你可以试试:

echo(strip_tags($your_string));

更多信息在这里:http://php.net/manual/en/function.strip-tags.php

【讨论】:

【解决方案2】:

另一种选择是使用 Html2Text。它会比 strip_tags 做得更好,特别是如果你想解析复杂的 HTML 代码。

从 HTML 中提取文本很棘手,因此最好的办法是使用为此目的构建的库。

https://github.com/mtibben/html2text

使用作曲家安装:

composer require html2text/html2text

基本用法:

$html = new \Html2Text\Html2Text('Hello, &quot;<b>world</b>&quot;');

echo $html->getText();  // Hello, "WORLD"

【讨论】:

    【解决方案3】:

    为可能需要此功能的其他人添加另一个选项,Stringizer 库可能是一个选项,请参阅Strip Tags

    完全披露我是该项目的所有者。

    【讨论】:

    • 很酷的项目,虽然内部使用了strip_tags() 你有什么想法制作一个处理内联css样式的函数吗?
    猜你喜欢
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多