duan201444 2013-08-07 22:24
浏览 83
已采纳

正则表达式解析url参数

I'm having trouble retrieving a URL parameter from a string using regular expressions:

An example string could be

some text and http://google.com/?something=this&tag=yahoo.com and more text, and I would like to be able to find yahoo.com from this.

The caveat is that I need to ensure that the string begins with http://google.com, and not just search for &tag=(.*)

preg_match("/google\.com\/.*&tag=(.*) $/", $subject, $matches)

i'm hoping this matches anything with google.com followed by anything, followed by &tag= followed by a space. Ultimately the goal is to parse out all of the tag= values from google.com URLs.

Is there a better way to accomplish this?

Update:

so I have this new regex: /google\.com\/.*(tag=.*)/ but i'm not sure how to get it to end on a space after the URL

  • 写回答

2条回答 默认 最新

  • doujing2017 2013-08-07 22:28
    关注

    get friendly with the parse_url() function!

    $pieces = parse_url('some text http://google.com/?something=this&tag=yahoo.com and whatever');
    $query = explode('&', $pieces['query']);
    
    parse_str($pieces['query'], $get);
    array_walk($get, function(&$item){
        if (!$sp = strpos($item, ' ')) return;
        $item = substr($item, 0, $sp);
    });
    
    var_dump($get); // woo!
    

    edit: thanks to Johnathan for the parse_str() function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误