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

Author - Kritika Sood

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);}
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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

Send your message