Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert special characters to html code with php

I need a function that will clean a strings' special characters. I do NOT want this to convert HTML characters like <br /> to &lt;br /&gt;

I want to convert things like: •, ½, ’ to html code.

This is the function I currently use, but it doesn't appear to work with the fractions..

function cleanText($str){

$str = str_replace("Ñ" ,"&#209;", $str);
$str = str_replace("ñ" ,"&#241;", $str);
$str = str_replace("ñ" ,"&#241;", $str);
$str = str_replace("Á","&#193;", $str);
$str = str_replace("á","&#225;", $str);
$str = str_replace("É","&#201;", $str);
$str = str_replace("é","&#233;", $str);
$str = str_replace("ú","&#250;", $str);
$str = str_replace("ù","&#249;", $str);
$str = str_replace("Í","&#205;", $str);
$str = str_replace("í","&#237;", $str);
$str = str_replace("Ó","&#211;", $str);
$str = str_replace("ó","&#243;", $str);
$str = str_replace("“","&#8220;", $str);
$str = str_replace("”","&#8221;", $str);

$str = str_replace("‘","&#8216;", $str);
$str = str_replace("’","&#8217;", $str);
$str = str_replace("—","&#8212;", $str);

$str = str_replace("–","&#8211;", $str);
$str = str_replace("™","&trade;", $str);
$str = str_replace("ü","&#252;", $str);
$str = str_replace("Ü","&#220;", $str);
$str = str_replace("Ê","&#202;", $str);
$str = str_replace("ê","&#238;", $str);
$str = str_replace("Ç","&#199;", $str);
$str = str_replace("ç","&#231;", $str);
$str = str_replace("È","&#200;", $str);
$str = str_replace("è","&#232;", $str);
$str = str_replace("•","&#149;" , $str);

$str = str_replace("¼","&#188;" , $str);
$str = str_replace("½","&#189;" , $str);
$str = str_replace("¾","&#190;" , $str);
$str = str_replace("½","&#189;" , $str);

return $str;

}
like image 822
Brandon Fredericksen Avatar asked May 05 '26 06:05

Brandon Fredericksen


2 Answers

You can replace your entire function with htmlentities using the ENT_SUBSTITUTE attribute. It will perform much faster in addition to working correctly.

Note: ENT_SUBSTITUTE available as of PHP 5.4.

like image 125
Levi Morrison Avatar answered May 06 '26 19:05

Levi Morrison


Guess it's time to take a look at the htmlentities PHP function, and its options.

Basically, you can replace your whole function with:

$str = htmlentities( $str );

It will be also a lot more efficient.

Be sure to take a look at the function's optional parameters, if you need special processing (especially ENT_SUBSTITUTE).

$str = htmlentities( $str, ENT_SUBSTITUTE );
like image 32
Macmade Avatar answered May 06 '26 19:05

Macmade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!