服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - php自定义函数实现JS的escape的方法示例

php自定义函数实现JS的escape的方法示例

2021-02-01 16:56HTL PHP教程

这篇文章主要介绍了php自定义函数实现JS的escape的方法,结合完整实例形式分析了php实现JS的escape功能函数的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了php自定义函数实现JSescape的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//php function
function escape($string) {
    $n = $bn = $tn = 0;
    $output = '';
    $special = "-_.+@/*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    while($n < strlen($string)) {
        $ascii = ord($string[$n]);
        if($ascii == 9 || $ascii == 10 || (32 <= $ascii && $ascii <= 126)) {
            $tn = 1;$n++;
        } elseif(194 <= $ascii && $ascii <= 223) {
            $tn = 2;$n += 2;
        } elseif(224 <= $ascii && $ascii <= 239) {
            $tn = 3;$n += 3;
        } elseif(240 <= $ascii && $ascii <= 247) {
            $tn = 4;$n += 4;
        } elseif(248 <= $ascii && $ascii <= 251) {
            $tn = 5;$n += 5;
        } elseif($ascii == 252 || $ascii == 253) {
            $tn = 6;$n += 6;
        } else {
            $n++;
        }
        $singleStr = substr($string,$bn,$tn);
        $charVal = bin2hex(iconv('utf-8', 'ucs-2', $singleStr));
        if(base_convert($charVal, 16, 10) > 0xff) {
           if (!preg_match("/win/i", PHP_OS))
            $charVal = substr($charVal, 2, 2).substr($charVal, 0, 2);
          $output .= '%u' . $charVal;
        }
        else {
            if(false !== strpos($special, $singleStr))
               $output .= $singleStr;
            else
               $output .="%" . dechex(ord($string[$bn]));
        }
     $bn = $n;
    }
    return $output;
}

希望本文所述对大家PHP程序设计有所帮助。

延伸 · 阅读

精彩推荐