将特殊HTML字符转换回原始字符串

时间:2012-08-21 21:24:47

标签: php html htmlspecialchars

我正在构建一个小的解析器来抓取网页并在其上记录数据。要记录的事情之一是论坛的帖子标题。我正在使用XML解析器来查看DOM并获取此信息,我将其存储如下:

// Strip out the post's title
$title = $page->find('a[rel=bookmark]', 0);
$title = htmlspecialchars_decode(html_entity_decode(trim($title->plaintext)));

这大部分都有效,但有些帖子有一些特殊的HTML字符代码,例如–,它是破折号(-)。我如何将这些特殊字符代码转换回原始字符串?

感谢。

3 个答案:

答案 0 :(得分:3)

使用html_entity_decode。这是一个简单的例子。

$string = "hyphenated&#8211words";

$new = html_entity_decode($string);

echo $new;

你应该看到......

hyphenated–words

答案 1 :(得分:0)

Documentation是你的朋友:

html_entity_decode(trim($title->plaintext), ENT_XHTML, YOUR_ENCODING);
                                            ^^^^^^^^^^^^^^^^^^^^^^^^

答案 2 :(得分:0)

这可能会有所帮助:

<?php
 function clean_up($str){
 $str = stripslashes($str);
 $str = strtr($str, get_html_translation_table(HTML_ENTITIES));
 $str = str_replace( array("\x82", "\x84", "\x85", "\x91", "\x92", "\x93", "\x94", "\x95", "\x96",  "\x97"), array("&#8218;", "&#8222;", "&#8230;", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8226;", "&#8211;", "&#8212;"),$str);
return $str;
}
?>
相关问题