簡體   English   中英

如何用PHP從HTML字符串中僅提取文本?

[英]How to extract only text from HTML string with PHP?

我想只從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。 我怎么能這樣做? 關於這種技術的任何想法和想法?

你可以嘗試:

echo(strip_tags($your_string));

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

另一種選擇是使用Html2Text。 它會比strip_tags做得好得多,特別是如果你想解析復雜的HTML代碼。

從HTML中提取文本很棘手,因此最好的辦法是使用為此目的而構建的庫。

https://github.com/mtibben/html2text

使用composer安裝:

composer require html2text/html2text

基本用法:

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

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

為可能需要此功能的其他人添加另一個選項, Stringizer庫可能是一個選項,請參閱Strip Tags

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM