php中的html字符串编码问题

php中的html字符串编码问题,php,html,encoding,entities,Php,Html,Encoding,Entities,我有一个包含html的字符串。 我如何对字符串进行加密,以便对除标记以外的所有内容进行编码? 例如: $foo = '<div class="link">Here\'s is a link: "<a href="http://www.example.com">Doors & windows</a>'</div>'; $foo='这里有一个链接:''; 我想把它转换成 $out = '<div class="link">Her

我有一个包含html的字符串。 我如何对字符串进行加密,以便对除标记以外的所有内容进行编码? 例如:

$foo = '<div class="link">Here\'s is a link: "<a href="http://www.example.com">Doors & windows</a>'</div>';
$foo='这里有一个链接:'';
我想把它转换成

$out = '<div class="link">Here\'s is a link: &quot;<a href="http://www.example.com">Doors &amp; windows</a>&quot;</div>';
$out='这里有一个链接:';

首先用另一个令牌替换括号,调用
htmlentities
,然后转换回

$html = str_replace("<","***OPENBRACKET***",$html);
$html = str_replace(">","***CLOSEBRACKET***",$html);

$html = htmlentities($html);

$html = str_replace("***OPENBRACKET***","<",$html);
$html = str_replace("***CLOSEBRACKET***",">",$html);
$html=str_replace(“,”***右括号***,$html);
$html=htmlentities($html);
$html=str_replace(“***开放括号***”,“”,$html);

此代码片段显示了一个函数,该函数将加载一些xml(确保至少打开的标记有一个结束挂件等,否则您将看到/读取一些错误),然后将
htmlentities
应用到所有文本节点上。我实际上不知道您需要什么,但它可能会让您感到高兴:

$foo = '<div class="link">Here\'s is a link: <a href="http://www.example.com">Doors & windows</a></div>';

echo text_htmlentities(utf8_encode($foo));

/**
 * add htmlentities onto the text-nodes of an
 * xml fragment.
 * 
 * @param string $foo xml fragment (utf8)
 * @return string
 */
function text_htmlentities($foo) {
    $foo = str_replace('&', '&amp;', $foo);
    $dom = new DOMDocument;
    $dom->loadXml($foo);
    $xpath = new DomXpath($dom);
    foreach($xpath->query('//text()') as $node) {
        $node->nodeValue = htmlentities($node->nodeValue, ENT_QUOTES, 'UTF-8', false);
    }
    return str_replace('&amp;','&', $dom->saveXml($dom->firstChild));
}
$foo='这里有一个链接:';
回显文本(utf8编码($foo));
/**
*将htmlentities添加到
*xml片段。
* 
*@param字符串$foo xml片段(utf8)
*@返回字符串
*/
函数文本\u htmlentities($foo){
$foo=str_replace(“&”、“&;”、$foo);
$dom=新的DOMDocument;
$dom->loadXml($foo);
$xpath=newdomxpath($dom);
foreach($xpath->query('//text()')作为$node){
$node->nodeValue=htmlentities($node->nodeValue,ENT_引号,'UTF-8',false);
}
返回str_replace(“&;”、“&”、$dom->saveXml($dom->firstChild));
}
输出:

<div class="link">Here&#039;s is a link: <a href="http://www.example.com">Doors &amp; windows</a></div>
这里是一个链接:

尝试使用必须是
$out=“您能解释一下为什么需要这个功能吗?因为我觉得这样做毫无意义。我只知道有两种情况需要htmlentities:(1)当我们想要生成规则文本或html属性值以不干扰html语言元素时。(2) 当需要显示一些来自不同字符集的特殊符号时,这个问题的答案很简单,我想要有效的html。我的字符串包含html,其中可能包含无效字符。我希望html元素保持不变,但对这些元素中的数据运行
htmlentities
。然后需要使用html解析器,并在文本节点上运行htmlentities。我开始怀疑是否有人理解我想要做的事情。。这是可行的,除了它只适用于xml之外,还有html的解决方案吗?@nathanjosiah哪个字符集使用您的页面?@nathanjosiah:更新了代码。函数需要一个utf8编码的字符串。-将ISO-8859-1字符串编码为UTF-8