Showing posts with label escape quotes in php. Show all posts
Showing posts with label escape quotes in php. Show all posts

Wednesday, December 25, 2013

How to escape quotes in php

Here i have paste two example of how to escape quotes in php we face always when we use php , html and javascript event combine.

First Example
<?php

echo $chkbox = '<input type="checkbox" name="pages" id="chk_'.$val['sb_id'].'" value="'.$val['sb_id'].'" onclick=\'assignSidebar('.$val['sb_id'].',"'.$val['sb_name'].'")\' />';

?>
Second Example
<?php

$name = "khan's";
$name = htmlentities(str_replace("'", "\'", $name));
echo $response = "<img src=\"images/action_delete.gif\" onClick=\"confirmDelete('" . $name . "')\"/>";

?>

php to encode special characters but not html tags

For Latin-1 you can escape characters easily with:
$html = preg_replace('/[\x80-\xFF]/e', '"&#x".dechex(ord("$0")).";"', $html);
For UTF-8 it's a bit more involving:
$html = preg_replace_callback("/(?!\w)\p{L}/u", "xmlent", $html);
function xmlent($m) {
    $str = mb_convert_encoding( $m[0] , "UCS-2BE", "UTF-8");
    return "&#x" . bin2hex($str) . ";";
}
Read More »