Home  >  Article  >  Backend Development  >  How to use PHP to implement javascript's escape and unescape functions_PHP Tutorial

How to use PHP to implement javascript's escape and unescape functions_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:02:241061browse

Front-end development engineers all know that JavaScript has the encoding function escape() and the corresponding decoding function unescape(), while PHP only has urlencode and urldecode. These encoding and decoding functions are valid for encodeURI and encodeURIComponent, but are invalid for escape.
The escape() function and unescape() function in JavaScript user string encoding, similar to the urlencode() function in PHP. The following is the escape function code implemented by PHP:

Copy code The code is as follows:

/**
 * js escape php 实现
 * @param $string           the sting want to be escaped
 * @param $in_encoding      
 * @param $out_encoding     
 */
function escape($string, $in_encoding = 'UTF-8',$out_encoding = 'UCS-2') {
$return = '';
if (function_exists('mb_get_info')) {
for($x = 0; $x < mb_strlen ( $string, $in_encoding ); $x ++) {
                    $str = mb_substr ($string, $x, 1, $in_encoding); 🎜>                  $return .= '%u' . strtoupper ( bin2hex ( ( mb_convert_encoding ( $str, $out_encoding, $in_encoding) ) )); toupper ( bin2hex ( $str ) );
                                                                                                                                                                                                                                                          >

Copy code

The code is as follows:


function unescape($str)
{
$ret = '';
$ len = strlen($str);
for ($i = 0; $i < $len; $i ++)
{
if ($str[$i] == '%' && $str[$i + 1] == 'u')                                                                                                           0x7f) $ret .= chr($val); else if ($val < 0x800)
$ret .= chr(0xc0 | ($val >> 6) ) . 2)) .
chr(0x80 | (($val >> 6) & 0x3f)) .
                                                    if ($ str [$ i] == '%')
{
$ Ret. = Urldecode (substr ($ Str, $ i, 3));
$ i += 2;
} else
               $ret .= $str[$i];

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327930.htmlTechArticleFront-end development engineers all know that javascript has the encoding function escape() and the corresponding decoding function unescape(), while in php There are only urlencode and urldecode. This encoding and decoding function works on encodeURI and...
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
Previous article:Parsing PHP into and out of the database_PHP tutorialNext article:Parsing PHP into and out of the database_PHP tutorial

Related articles

See more