1

我需要删除从 Petfinder API 返回的描述中的所有 HTML 标记,但我似乎无法弄清楚如何。

$data['description']保存返回的描述。我在源文件中看到的是这样的......

<div>some text that gets returned</div>

我试过用strip_tags,我试过用html_entity_decode,但标签不会消失!

我需要剥离标签,以便截断描述。

有人有想法么?

$data['description'] = (string)$pet->description;

$description = $data['description'];
$description = htmlentities($description);
$description = html_entity_decode($description);
$description = strip_tags($description);

$description = substr($data['description'],0,300);
$description = substr($description,0,strrpos($description,' '));
$description = $description."...";

echo "<span style='text-align: justify; margin: 10px 0px;'>".$description."</span>";
4

2 回答 2

2

问题是你先跑htmlentities。在这之后strip_tags不能再工作了。

只需这样做:

$test = '<div>some text that gets returned</div>';
echo strip_tags($test);

硬核方式:

$doc = new DOMDocument();
$doc->loadHTML('<div>some text that gets returned</div>');
$items = $doc->getElementsByTagName('div');
$content = $items->item(0)->nodeValue;
echo $content;
于 2013-03-06T01:48:47.040 回答
2

问题是您在处理过程中再次使用原始输入:

$description = $data['description'];
$description = htmlentities($description);
$description = html_entity_decode($description);
$description = strip_tags($description);

$description = substr($data['description'],0,300);
                      ^^^^^^^^^^^^^^^^^^^^ All previous changes undone!
$description = substr($description,0,strrpos($description,' '));
$description = $description."...";

除此之外,@redreggae 是对的,你只需要strip_tags.

于 2013-03-06T01:59:47.083 回答