如何检查preg_match的复杂文本?

问题描述 投票:0回答:1

我已经看过一些关于它的帖子,但我的文字有点复杂,

我无法让它发挥作用。

我页面的一部分:

otherurl":"http:\/\/cdn1-test.peer5.net:80\/edge\/71-1.stream\/playlist.m3u8?uid=35577\u0026sil=3\u0026sip=WyIxODUuMTgueC54IiwiMjEwLj4LngiLCI54LngLjE1OC5giXQ%3D%3D\u0026sid=151078248\u0026misc=4OFxyLUs7UrIeWujPzuU%3D"}}

我尝试了什么:

preg_match("/otherurl":"http:\/\/cdn1-test.peer5.net:80\/edge\/71-1.stream\/playlist.m3u8?uid=(.*)/", $data[$n], $output);
echo $output[1];

我想要呈现的内容:

只是uid后面的数字= *

php preg-match
1个回答
1
投票

如果您收到的字符串格式可靠,就像您发布的示例一样,其中uid=参数是?之后的第一个查询参数,并且严格来说是一个数字字符串,您可以使用preg_match()通过匹配(\d+)(匹配数字)来提取它,因为无论后面是什么下一个查询参数不会以数字开头。

$str = 'otherurl":"http:\/\/cdn1-test.peer5.net:80\/edge\/71-1.stream\/playlist.m3u8?uid=35577\u0026sil=3\u0026sip=WyIxODUuMTgueC54IiwiMjEwLj4LngiLCI54LngLjE1OC5giXQ%3D%3D\u0026sid=151078248\u0026misc=4OFxyLUs7UrIeWujPzuU%3D"}}';

preg_match('/\?uid=(\d+)/', $str, $output);
echo $output[1];
// Prints "35577"

在实践中,我会避​​免这种情况。处理此问题的最佳方法是将其视为JSON流,并结合PHP的内置URL处理方法parse_url()parse_str()

该解决方案如下:

// Note: I made this segment a valid JSON string...
$input_json = '{"otherurl":"http:\/\/cdn1-test.peer5.net:80\/edge\/71-1.stream\/playlist.m3u8?uid=35577\u0026sil=3\u0026sip=WyIxODUuMTgueC54IiwiMjEwLj4LngiLCI54LngLjE1OC5giXQ%3D%3D\u0026sid=151078248\u0026misc=4OFxyLUs7UrIeWujPzuU%3D"}';

$decoded = json_decode($input_json, TRUE);
// Parse the URL and extract its query string
// PHP_URL_QUERY instructs it to get only the query string
// but if you ever need other segments that can be removed
$query = parse_url($decoded['otherurl'], PHP_URL_QUERY);
// Parse out the query string into array $parsed_params
$params = parse_str($query, $parsed_params);
// Get your uid.
echo $parsed_params['uid'];
// Prints 35577
© www.soinside.com 2019 - 2024. All rights reserved.