我的文字是:
u0026itag=22\u0026url=http%3A%2F%2Fr5---sn-q4f7dnel.c.youtube.com\u0026sig
我想解析u0026url 我的 PHP 代码:
preg_match('/u0026itag=22\u0026url=(.*?)/', $part, $A);
echo $A[1];
但它没有给我结果
我的文字是:
u0026itag=22\u0026url=http%3A%2F%2Fr5---sn-q4f7dnel.c.youtube.com\u0026sig
我想解析u0026url 我的 PHP 代码:
preg_match('/u0026itag=22\u0026url=(.*?)/', $part, $A);
echo $A[1];
但它没有给我结果
First a tip: If you enable errors, PHP tells you about what is going wrong. When I first copied your code verbatim I got the following warning reported:
Warning: preg_match(): Compilation failed: PCRE does not support \L, \l, \N{name}, \U, or \u at offset 14
So this is already a hint that some sequence you put in there verbatim is being parsed as the regex and therefore it requires escaping or quoting. I prefered quoting here, that is wrapping in \Q at the beginning and \E at the end (QuotE):
$result = preg_match('/^\Qu0026itag=22\u0026url=\E(.*?)/', $subject, $matches);
## ##
Which then prevents to see an error and turning $result
to 1 which means it did work. However you still don't see any matches in group 1 or better said you see an empty match:
[0] => string(22) "u0026itag=22\u0026url="
[1] => string(0) ""
That is because you turned the repetition with star from greedy to lazy. Let's make it possesive instead:
/^\Qu0026itag=22\u0026url=\E(.*+)/
# plus means posessive
[1] => string(52) "http%3A%2F%2Fr5---sn-q4f7dnel.c.youtube.com\u0026sig"
Okay this looks better and it contains the "URL".
Which brings me to the point: Even I explained you some for the regex (hopefully this gave some pointers), it's actually probably not the right tool to use first.
What you have here looks like some JSON string that indeed contains something that is URL encoded.
I therefore suggest that you first decode the JSON string with json_decode
, then parse the URL with parse_url
and all you then need to do is to obtain the url
query parameter. That is with parse_str
.
您是否尝试过使用贪婪匹配http://regex101.com/r/lT1wK5?记住也要避开 \u,否则你会得到
编译失败:PCRE 不支持 \L、\l、\N{name}、\U 或 \u
例子:
$var = "u0026itag=22\u0026url=http%3A%2F%2Fr5---sn-q4f7dnel.c.youtube.com\u0026sig";
preg_match('/u0026itag=22\\\u0026url=(.*)/', $var, $A);
echo $A[1];