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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算