Reverse preg_replace

后端 未结 1 1569
名媛妹妹
名媛妹妹 2020-12-17 04:16

I have regex like this:

^page/(?P\\d+)-(?P[^\\.]+)\\.html$

and an array:

$args = array(
    \'id\' =&         


        
相关标签:
1条回答
  • 2020-12-17 04:58

    Interesting challenge, I coded something that works for this sample, note that you need PHP 5.3+ for this code to work:

    $regex = '^page/(?P<id>\d+)-(?P<slug>[\.]+)\.html$';
    $args = array(
        'id' => 5,
        'slug' => 'my-first-article'
    );
    
    $result = preg_replace_callback('#\(\?P<(\w+)>[^\)]+\)#', function($m)use($args){
        if(array_key_exists($m[1], $args)){
            return $args[$m[1]];
        }
    }, $regex);
    
    $result = preg_replace(array('#^\^|\$$#', '#\\\\.#'), array('', '.'), $result); // To remove ^ and $ and replace \. with .
    echo $result;
    

    Output: page/5-my-first-article.html

    Online demo.

    0 讨论(0)
提交回复
热议问题