Home >Backend Development >PHP Tutorial >PHP implements the escape and unescape functions in JavaScript

PHP implements the escape and unescape functions in JavaScript

WBOY
WBOYOriginal
2016-07-25 08:43:19902browse
escape函数
  1. /**
  2. * js escape php 实现
  3. * @param $string the sting want to be escaped
  4. * @param $in_encoding
  5. * @param $out_encoding
  6. */
  7. function escape($string, $in_encoding = 'UTF-8',$out_encoding = 'UCS-2') {
  8. $return = '';
  9. if (function_exists('mb_get_info')) {
  10. for($x = 0; $x < mb_strlen ( $string, $in_encoding ); $x ++) {
  11. $str = mb_substr ( $string, $x, 1, $in_encoding );
  12. if (strlen ( $str ) > 1) { // 多字节字符
  13. $return .= '%u' . strtoupper ( bin2hex ( mb_convert_encoding ( $str, $out_encoding, $in_encoding ) ) );
  14. } else {
  15. $return .= '%' . strtoupper ( bin2hex ( $str ) );
  16. }
  17. }
  18. }
  19. return $return;
  20. }
复制代码
unescape代码:
  1. function unescape($str)
  2. {
  3. $ret = '';
  4. $len = strlen($str);
  5. for ($i = 0; $i < $len; $i ++)
  6. {
  7. if ($str[$i] == '%' && $str[$i + 1] == 'u')
  8. {
  9. $val = hexdec(substr($str, $i + 2, 4));
  10. if ($val < 0x7f)
  11. $ret .= chr($val);
  12. else
  13. if ($val < 0x800)
  14. $ret .= chr(0xc0 | ($val >> 6)) .
  15. chr(0x80 | ($val & 0x3f));
  16. else
  17. $ret .= chr(0xe0 | ($val >> 12)) .
  18. chr(0x80 | (($val >> 6) & 0x3f)) .
  19. chr(0x80 | ($val & 0x3f));
  20. $i += 5;
  21. } else
  22. if ($str[$i] == '%')
  23. {
  24. $ret .= urldecode(substr($str, $i, 3));
  25. $i += 2;
  26. } else
  27. $ret .= $str[$i];
  28. }
  29. return $ret;
  30. }
复制代码
javascript, php, unescape


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn