我知道javascript默认情况下会忽略反斜杠\字符。我正在尝试用PHP和PHP编写两个方法;Javascript哪些方法应该给出相同的输出。
示例:以下是原始字符串".\+*?[^]$(({}=<gt;|:-">
在阅读了原始字符串中的每个字符后,我得到了以下结果:
- 在PHP中:".\+*?[^]$(({}=<gt;|:-">
转义字符串为:".\\\\+\*\\[\^\]\$\(\(\{\}\=\\<>\ | \:\-">
降级后的字符串为:".\+*?[^]$(({}=<gt;|:-"(与原件一样(
- 在Javascript中:.+*?[^]$(({}=<gt;|:-(丢失反斜杠\字符(
转义字符串为:"\.\+\*\\[\^\]\$\(\(\{\}\=\\<>\ | \:\-"(与PHP不同,因为在读取方法中丢失了反斜杠\字符(
降级后的字符串是:".+*?[^]$(({}=<gt;|:-"(带有丢失的反斜杠\字符(
我如何才能获得PHP和amp;JS用于任何给定的字符串,包括反斜杠\字符
以下是PHP和PHP中的代码;JS-
-
PHP
class Constants { /* List of following special characters : [.+*?[^]$(){}=!<>|:-] */ public static $ESCAPEDCHARS = [".", "\", "+", "*", "?", "[", "^", "]", "$", "(", ")", "{", "}", "=", "!", "<", ">", "|", ":", "-"]; public static $SLASH = "\"; public static function escapedArrayHasChar($char) { foreach (Constants::$ESCAPEDCHARS as $value) { if (strcmp($value, $char) === 0) { return true; } } return false; }} class Tools { public static function escaped($str) { $length = strlen($str); $result = ""; for ($index = 0; $index < $length; $index++) { if (Constants::escapedArrayHasChar($str[$index])) { $result .= Constants::$SLASH . $str[$index]; } else { $result .= $str[$index]; } } return $result; } public static function descaped($str) { $length = strlen($str); $result = ""; for ($index = 0; $index < $length - 1; $index++) { if (strcmp(Constants::$SLASH, $str[$index]) === 0 && Constants::escapedArrayHasChar($str[$index + 1])) { $result .= $str[$index + 1]; $index++; } else { $result .= $str[$index]; } if ($index === $length - 2) { $result .= $str[$index + 1]; } } return $result; }}
-
JAVASCRIPT
$(function () { /*List of following special characters : [.+*?[^]$(){}=!<>|:-] */ var ESCAPEDCHARS = [".", "\", "+", "*", "?", "[", "^", "]", "$", "(", ")", "{", "}", "=", "!", "<", ">", "|", ":", "-"]; var SLASH = "\", DOUBLESLASH = "\\"; $.equals = function (str1, str2) {return str1 === str2;}; $.escapedArrayHasChar = function (cr) { var index = 0; for (index = 0; index< ESCAPEDCHARS.length; index++) { if ($.equals(ESCAPEDCHARS[index], cr)) { return true; } } return false; }; $.escaped = function (str) { var length = str.length; var result = "", index = 0; for (index = 0; index < length; index++) { if ($.escapedArrayHasChar(str[index])) { result += SLASH + str[index]; } else { result += str[index]; } } return result; }; $.descaped = function (str) { var length = str.length; var result = "", index = 0; for (index = 0; index < length - 1; index++) { if ($.equals(SLASH, str[index]) && $.escapedArrayHasChar(str[index + 1])){ result += str[index + 1]; index++; }else { result += str[index]; } if (index === length - 2) { result += str[index + 1]; } } return result; }; });
我认为唯一的解决方案是确保将2个反斜杠导入到任何需要检查的字符串中。如果字符串中的\字符有两个反斜杠,则PHP&JS给出相同的输出。
好吧,这似乎需要很多代码来处理这个问题——我可能会选择编码。例如,在base64编码中,该字符串为:"LlwrKj9bXl0kKCl7fT0hPD58Oi0=";。在php中,base64_decode
将返回您的字符串,在javascript中atob
也将返回它。在一般情况下,您可以使用base64_encode
创建编码,并使用btoa
在javascript中创建编码。