PHP - 将带有 - 或+符号的字符串转换为HTML

时间:2011-01-18 01:09:15

标签: php html string

如何将具有-+符号的字符串转换为html友好字符串? 我的意思是将这些字符转换为html符号,例如空格为 等等......

ps:htmlentities不起作用。我仍然看到 - / +

6 个答案:

答案 0 :(得分:2)

试试这个

$string = str_replace('+', '+', $string); // Convert + sign
$string = str_replace('-', '-', $string); // Convert - sign

答案 1 :(得分:1)

我认为这些符号的实体不会看到:http://www.w3schools.com/tags/ref_entities.asp

我用

进行了测试
$str = "- and +"; echo htmlentities($str);

并没有获得实体。根据:http://us.php.net/manual/en/function.htmlentities.php

如果有可用的编码,我希望它们能被编码。

答案 2 :(得分:1)

不知道你想要完成什么。但这会将所选字符转义为html实体:

$html = preg_replace("/([+-])/e", '"&#".ord("$1").";"', $html);

答案 3 :(得分:1)

据我所知, - 和HTML在HTML中很好,并且没有相应的实体。见http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

您确定没有考虑过网址编码吗?

答案 4 :(得分:1)

指定您希望它使用unicode,如下所示:

htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");

答案 5 :(得分:1)

查看此页面上的第二条评论:

http://www.php.net/manual/en/function.htmlentities.php#100388

这将启用更多编码字符。

如果你只是想对某些进行编码,那么这个重量要轻一些:

<?php 
$ent = array( 
    '+'=>'&#43;',
    '-'=>'&#43;'
); 

echo strtr('+ and -', $ent); 
?>