douyin9987 2013-06-06 18:55
浏览 76
已采纳

url参数替换的正则表达式

I've done little with Regex, but I know this has to be simpler than I'm making it.

Given a URL that looks like this:

/p1/p2/{p3}/{p4}/.../{pn}

where {p3}, {p4} contain keys to an associate array.

I want to replace the values in the braces with the value in the braces (more specifically, a value in an associative array where this is the key)

So this ultimately becomes

/p1/p2/p3/p4 and ultimately /p1/p2/v3/v4

I suppose I could just replace the '{}' with empty, but I want the replacement string to match the contents of the original expression exactly so the lookup in the array works.

I'm using the PHP function preg_replace.

/(\w+)/({\w+})/ doesn't quite work...

  • 写回答

3条回答 默认 最新

  • dongzhun1857 2013-06-06 19:33
    关注

    While I'm not sure if I parsed your question right, this might a possible solution:

    $pattern = "/p1/p2/{p4}/{p5}/foo/bar/baz";
    $values = array(
        'p4' => 'eggs',
        'p5' => 'spam',
    );
    
    $pattern_fixed = preg_replace_callback("#{(.*?)}#", function ($match) use ($values) {
        return isset($values[$match[1]]) ? $values[$match[1]] : $match[1];
    }, $pattern);
    
    var_dump($pattern_fixed);
    

    Output:

    string(28) "/p1/p2/eggs/spam/foo/bar/baz"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试