Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named backreferences with preg_replace

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

// should match, replace, and output: user/profile/foo
$string = 'user/foo';
echo preg_replace('#^user/(?P<id>[^/]+)$#Di', 'user/profile/(?P=id)', $string);

This is a trivial example, but I'm wondering if this syntax, (?P=name) is simply not supported. Syntactical issue, or non-existent functionality?

like image 817
Dan Lugg Avatar asked Mar 10 '11 03:03

Dan Lugg


3 Answers

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<id>[^/]+)$#Di', 'my_replace', $string);

Or even quicker

$newandimproved = preg_replace('#^user/([^/]+)$#Di', '/user/profile/$1', $string);
like image 52
Dimitry Avatar answered Nov 04 '22 22:11

Dimitry


preg_replace does not support named backreferences.

preg_replace_callback supports named backreferences, but after PHP 5.3, so expect it to fail on PHP 5.2 and below.

like image 21
Thai Avatar answered Nov 05 '22 00:11

Thai


preg_replace does not supported named subpatterns yet.

like image 2
codaddict Avatar answered Nov 04 '22 22:11

codaddict