[英]preg_match behaviour unexpected on string \x00\x01
我有一个有时包含此数据的循环: b"\\x01\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x00X\\x1D›¿\\x04\\x04›?‹„\\x12¿Ã'\\x11?"
当我将其放入regex101中时,可以使用以下正则表达式来匹配项:/(( /((\\\\x[\\d]{2}){4,}.*)/gm
参见示例: https : //regex101.com/r/cMyKVg/1/
当我将其放在我的php脚本中时,它是这样的:
preg_match( '/(x)/m', $value, $matches )
$value
具有上面字符串的值。
我没有使用此代码的匹配项。 我也尝试过从字面上进行匹配:
preg_match( '/((\\x[\d]{2}){4,}.*)/m', 'b"\x01\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00X\x1D›¿\x04\x04›?‹„\x12¿Ã’\x11?"', $matches ),
但这不符合任何条件。
我不想在数据库中使用此值,因此我想使用正则表达式跳过此类值。
有人可以向我解释这种行为,也许可以帮助解决它?
编辑:我有种感觉,我使用的字符串实际上不是preg_match
,它是我通过var_dump
获得的值,但似乎preg_match
获得了不同的值。 我无意中输入了一个错误,然后收到以下消息:
ErrorException : preg_match(): Compilation failed: missing ) at offset 3
at /Users/used/Sites/project/app/Console/Commands/ExtractLibraryFileMetaData.php:204
200| dd(
201| $value,
202| \gettype($value),
203| $regex = '/(\\)/',
> 204| preg_match( $regex, $value, $matches ),
205| $matches
206| );
207| }
208| if ( preg_match( '/((\\x[\d]{2}){4,}.*)/m', $value ) ) {
Exception trace:
1 preg_match("/(\)/", "\\\\\\\\\\X���?���Ò?")
我不知道是什么原因造成的。 它仍然是相同的值,但是显示方式不同...
十六进制字符不被视为字符串,字符串的实际输出可能是:
b"X›¿›?‹„¿Ã’?"
然后,您可以使用十六进制范围进行匹配:
// I double-quoted the string
$str = "b\"\x01\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00X\x1D›¿\x04\x04›?‹„\x12¿Ã’\x11?\"";
// Matches characters from char code 0 to 31
preg_match_all('/([\x00-\x1F])/', $str, $m);
输出:
echo '<pre>' . print_r($m[0], true) . '</pre>';
/*
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
[10] =>
[11] =>
[12] =>
[13] =>
[14] =>
[15] =>
[16] =>
)
*/
更换:
echo preg_replace('/([\x00-\x1F])/', '', $str);
// b"X›¿›?‹„¿Ã’?"
出于某种原因,PHP中的preg_match似乎需要三个反斜杠才能正确地转义\\ x。 我用此正则表达式preg_match('/((?:\\\\\\x[\\d]{2}){4,}.*)/m', $str, $matches)
,它正常工作。
您可以在此处找到现场演示: http : //sandbox.onlinephpfunctions.com/code/4aecc4bf25ec82a98c8fbaee32b34693f3316f64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.