开发者

Replace characters in a string with their HTML coding

开发者 https://www.devze.com 2023-02-15 00:18 出处:网络
I need to replace characters in a string with their HTML coding. Ex. The \"quick\" brown fox, jumps over the laz开发者_C百科y (dog).

I need to replace characters in a string with their HTML coding.

Ex. The "quick" brown fox, jumps over the laz开发者_C百科y (dog).

I need to replace the quotations with the & quot; and replace the brakets with & #40; and & #41;

I have tried str_replace, but I can only get 1 character to be replaced. Is there a way to replace multiple characters using str_replace? Or is there a better way to do this?

Thanks!


I suggest using the function htmlentities().

Have a look at the Manual.


PHP has a number of functions to deal with this sort of thing:

Firstly, htmlentities() and htmlspecialchars().

But as you already found out, they won't deal with ( and ) characters, because these are not characters that ever need to be rendered as entities in HTML. I guess the question is why you want to convert these specific characters to entities? I can't really see a good reason for doing it.

If you really do need to do it, str_replace() will do multiple string replacements, using arrays in both the search and replace paramters:

$output = str_replace(array('(',')'), array('&#40','&#41'), $input);

You can also use the strtr() function in a similar way:

$conversions = array('('=>'(', ')'=>')');
$output = strtr($conversions, $input);

Either of these would do the trick for you. Again, I don't know why you'd want to though, because there's nothing special about ( and ) brackets in this context.

While you're looking into the above, you might also want to look up get_html_translation_table(), which returns an array of entity conversions as used in htmlentities() or htmlspecialchars(), in a format suitable for use with strtr(). You could load that array and add the extra characters to it before running the conversion; this would allow you to convert all normal entity characters as well as the same time.

I would point out that if you serve your page with the UTF8 character set, you won't need to convert any characters to entities (except for the HTML reserved characters <, > and &). This may be an alternative solution for you.

You also asked in a separate comment about converting line feeds. These can be converted with PHP's nl2br() function, but could also be done using str_replace() or strtr(), so could be added to a conversion array with everything else.

0

精彩评论

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

关注公众号