PHP | Convert Special Characters to HTML entities without using htmlspecialchars( ) function

|
| By Webner

We can’t use special characters like >,<,”,’ etc directly in code because browser mixes these characters with HTML tags and gets confused. So we can use HTML entities if we want to use special characters in our code.

Below are some common entities which we can use in our code:

“ >“ – &gt
“< “ – &lt
“ & “ – &amp
‘ “ ‘ – &quot
“ ‘ “ – ‘

For Example,In PHP we want to display value of $cname variable which may contain html characters:

 <div class='listViewSpan' id=' ".$divid." '>".$cname."</div>"
 $cname=$name;  //$name can be any string containing special characters
 //replace “‘ ” with ' and similarly replace other characters
 if (strpos($cname, " ' " ) !== false) {$cname = str_replace(" ' ", "'", $cname);}
 elseif(strpos($cname, ">") !== false) { $cname = str_replace(">", "&gt", $cname);}   
 elseif(strpos($cname, "<") !== false){$cname = str_replace("<", "&lt", $cname);}
 elseif(strpos($cname, "&") !== false){$cname = str_replace("&", "&amp",$cname);} 
 elseif(strpos($cname, ' " ') !== false){$cname = str_replace('"', "&quot", $cname);}

Leave a Reply

Your email address will not be published. Required fields are marked *