all this functions like htmlspecialchars()
, htmlentities()
, html_entities_decode()
, urldecode()
e.t.c it's like a mess. So, i decided to build my own function that will do exactly what i need it to do, by combining functionalities of each. The problem is the lines that i have comment out in the array. I want to encode the chars "& # ;" but if i do so, my function will also encode the encoded chars.
Is there a way to encode this chars if there are not been a part of encoded elements in the table ? (the table could grow more in the future ...)
This is my function:
function my_htmlspecialchars($string, $type='encode')
{
$all = array(
'΄' => '´',
'\\' => '\',
'\'' => ''',
'"' => '"',
'|' => '|',
'~' => '~',
'{' => '{',
'}' => '}',
'€' => '€',
// '&' => '&',
':' => ':',
'!' => '!',
'@' => '@',
'+' => '+',
'=' => '=',
'^' => '^',
'$' => '$',
'*' => '*',
'%' => '%',
'?' => '?',
// '#' => '#',
// ';' => ';',
'`' => '`',
',' => ',',
'.' => '.',
'(' => '(',
')' => ')',
'[' => '[',
']' => ']',
'<' => '<',
'>' => '>'
);
$count = 0;
$output = $string;
// do the work
switch($type)
{
case "encode":
$output = str_replace(array_keys($all), $all, $string, $count);
break;
case "decode":
$output = str_replace($all, array_keys($all), $string, $count);
break;
}
return $output;
}
Usage example:
$orgText = "\"' $ # @ % & <p>test</p> <span>test2</span>";
$orgText .= ": ; ? ! @ + = & ` ΄ ' \" < > ( ) { } \\ | [ ] ~ ^ * # , . % € ";
echo 'org: '.$orgText."<br>";
## $myText = htmlspecialchars($myText, ENT_QUOTES);
# echo 'sch: '.$myText."<br>";
$encode = htmlentities($orgText, ENT_QUOTES);
echo 'entities encode: '.$encode."<br>";
$decode = html_entity_decode($encode, ENT_QUOTES, 'UTF-8')."<br>";
echo 'entities decode1: '.$decode;
echo 'entities decode2: '.html_entity_decode($decode, ENT_QUOTES, 'UTF-8')."<br>";
$myEncode = my_htmlspecialchars($orgText, 'encode');
echo 'my encode: '.$myEncode."<br>";
$myDecode = my_htmlspecialchars($myEncode, 'decode');
echo 'my decode: '.$myDecode."<br>";
/* The output in a browser should be:
"' $ # @ % &
test
test2: ; ? ! @ + = & ` ΄ ' " < > ( ) { } \ | [ ] ~ ^ * # , . % €
*/
The output of the above example is (in a browser):
org: "' $ # @ % & <p>test</p> test2: ; ? ! @ + = & ` ΄ ' " < > ( ) { } \ | [ ] ~ ^ * # , . % €
entities encode: "' $ # @ % & <p>test</p> <span>test2</span>: ; ? ! @ + = & ` � ' " < > ( ) { } \ | [ ] ~ ^ * # , . % �
entities decode1: "' $ # @ % & <p>test</p> test2: ; ? ! @ + = & ` � ' " < > ( ) { } \ | [ ] ~ ^ * # , . % �
entities decode2: "' $ # @ % &
test
test2: ; ? ! @ + = & ` � ' " < > ( ) { } \ | [ ] ~ ^ * # , . % �
my encode: "' $ # @ % & <p>test</p> <span>test2</span>: ; ? ! @ + = & ` ´ ' " < > ( ) { } \ | [ ] ~ ^ * # , . % €
my decode: "' $ # @ % &
test
test2: ; ? ! @ + = & ` ΄ ' " < > ( ) { } \ | [ ] ~ ^ * # , . % €
I think that the solution has to do something by using preg_replace() but i can't figure out how.