The example in this article describes how to implement JS escape using PHP custom functions. Share it with everyone for your reference, the details are as follows:
//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; }
Readers who are interested in more PHP-related content can check out the special topics of this site: "Summary of PHP Encoding and Transcoding Operation Skills", "php String Usage" Summary", "Complete PHP array (Array) operation skills", "php sorting algorithm summary", "PHP common traversal algorithms and techniques summary", "PHP data structure and algorithm tutorial", "php programming algorithm summary", "PHP Summary of Mathematical Operation Skills", "Summary of PHP Regular Expression Usage", "Summary of PHP Operation and Operator Usage" and "Summary of PHP Common Database Operation Skills"
I hope this article will be helpful to everyone in PHP programming.
The above has introduced examples of how to implement JS escape using js functions and PHP custom functions, including the content of js functions. I hope it will be helpful to friends who are interested in PHP tutorials.