Named backreferences with preg_replace

前端 未结 4 1123
说谎
说谎 2021-01-04 11:30

Pretty straightforward; I can\'t seem to find anything definitive regarding PHP\'s preg_replace() supporting named backreferences:

// should mat         


        
4条回答
  •  自闭症患者
    2021-01-04 11:33

    They exist:

    http://www.php.net/manual/en/regexp.reference.back-references.php

    With preg_replace_callback:

    function my_replace($matches) {
        return '/user/profile/' . $matches['id'];
    }
    $newandimproved = preg_replace_callback('#^user/(?P[^/]+)$#Di', 'my_replace', $string);
    

    Or even quicker

    $newandimproved = preg_replace('#^user/([^/]+)$#Di', '/user/profile/$1', $string);
    

提交回复
热议问题