dougua2309 2017-12-23 13:32
浏览 28
已采纳

如何检查preg_match的复杂文本?

I've already seen some posts about it, but my text is a bit complicated,

And I can not get it to work.

Part of my page:

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"}}

What I tried:

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

What I want to present:

Just the number after uid=*

  • 写回答

1条回答 默认 最新

  • dpcj32769 2017-12-23 13:50
    关注

    If the string you receive is reliably formatted like your posted examples, where the uid= parameter is the first query parameter after ? and is strictly a numeric string, you can use preg_match() to extract it by matching with (\d+) (match digits) because whatever follows in the next query parameter won't begin with a digit.

    $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"
    

    In practice I would avoid this though. The best way to handle this is to treat it as the JSON stream it is, in combination with PHP's built-in URL handling methods parse_url() and parse_str().

    That solution looks like:

    // 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi