所有这些功能,例如htmlspecialchars()
,htmlentities()
,html_entities_decode()
,urldecode()
e.t.c,它就像一团糟。因此,我决定构建我自己的函数,通过组合每个函数来完成我需要它做的事情。问题是我在数组中注释掉的行。我想编码字符"& #;"但如果我这样做,我的函数也将编码编码的字符。
如果表中没有编码元素的一部分,有没有办法对这个字符进行编码? (未来桌子可能会增长......)
这是我的功能:
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;
}
用法示例:
$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: ; ? ! @ + = & ` ΄ ' " < > ( ) { } \ | [ ] ~ ^ * # , . % €
*/
以上示例的输出是(在浏览器中):
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: ; ? ! @ + = & ` ΄ ' " < > ( ) { } \ | [ ] ~ ^ * # , . % €
我认为解决方案必须通过使用preg_replace()来做某事,但我无法弄清楚如何。