开发者

PHP - convert a string with - or + signs to HTML

开发者 https://www.devze.com 2023-02-05 00:47 出处:网络
How do I convert a string that has a - or + sign to a html friendly string? I mean to convert those characters to html notations, like spac开发者_开发问答e is   and so on...

How do I convert a string that has a - or + sign to a html friendly string? I mean to convert those characters to html notations, like spac开发者_开发问答e is   and so on...

ps: htmlentities doesn't work. I still see the -/+


Try this

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


I don't think there is entities for these symbols see: http://www.w3schools.com/tags/ref_entities.asp

I tested with

$str = "- and +"; echo htmlentities($str);

and didn't get entities. According to: http://us.php.net/manual/en/function.htmlentities.php

I would expect them to be encoded if there was encoding available.


No idea what you want to accomplish. But this escapes selected characters to html entities:

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


As far as I am aware, - and + are fine in HTML, and dont have an entity equivalent. See http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

Are you sure you're not thinking of URL encoding?


Specify that you want it to use unicode as follows:

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


Have a look at the 2nd comment on this page:

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

This will enable more encoding characters.

If you just want to encode some, then this is a little lighter weight:

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号