转义字符串中的奇怪斜杠组合

Escaping strange slash combination in string

嘿伙计们知道我将如何进行 preg 匹配以下字符串吗?

$str = "[=10=]/";

我似乎找不到转义斜杠的正确方法...

preg_match("/\\[=11=]/\\/", $str);

...只是我尝试过但都失败的多种方法之一。

正如评论中指出的那样,使用 "[=13=]/" 意味着您实际上拥有 chr(0)/ 我认为您的意思是 '[=16=]/' 没有特殊的转义。

你的正则表达式的问题是/。正则表达式需要包含在分隔符中,它实际上不必是 /。但是,如果您想使用它,您使用的任何定界符都必须在实际的正则表达式中转义。你没有这样做。正确的方法是:

preg_match('/\\0\//', '[=10=]/', $m);

或使用不同的分隔符:

preg_match('~\\0/~', '[=11=]/', $m);

但是如果您真的想为 "[=13=]/"chr(0) . '/' 找到一个正则表达式:

preg_match('/\0\//', "[=12=]/", $m); // or

preg_match('~\0/~', "[=12=]/", $m); // or

preg_match('/[=12=]\//', "[=12=]/", $m); // or

preg_match('~[=12=]/~', "[=12=]/", $m);

你需要弄清楚[=12=]是代表一个空字节0x00还是一个反斜杠后跟一个零的文字串。

在任何一种情况下,您都应该使用 preg_quote() 来正确转义您希望匹配的文字字符串。

$tgt_null    = "[=10=]/";
$tgt_literal = '[=10=]/';

$str_null    = "foo [=10=]/ bar";
$str_literal = 'foo [=10=]/ bar';

var_dump(
    preg_quote($tgt_null, '/'),
    preg_match('/'.preg_quote($tgt_null, '/').'/', $str_null),
    preg_match('/'.preg_quote($tgt_null, '/').'/', $str_literal),
    preg_quote($tgt_literal, '/'),
    preg_match('/'.preg_quote($tgt_literal, '/').'/', $str_null),
    preg_match('/'.preg_quote($tgt_literal, '/').'/', $str_literal)
);

结果:

string(6) "[=11=]0\/"
int(1)
int(0)
string(5) "\0\/"
int(0)
int(1)