Ersin Güvenç
Ersin Güvenç

Reputation: 311

How to i replace regex patterns using preg_replace function?

I have url like below

/test/(?<name>\w+)/(?<id>\d+)/

I want to replace it using preg_replace() function like this

/test/name/(?<id>\d+)/

I tried this but it does not work as i expected.

$subject = '/test/(?<name>\w+)/(?<id>\d+)/';

preg_replace('#\(.*\<name\>.*\)#', 'name', $subject);

Upvotes: 1

Views: 48

Answers (1)

Syscall
Syscall

Reputation: 19780

You could take all the characters until the next ")" using [^)]+.

$subject = '/test/(?<name>\w+)/(?<id>\d+)/';
$subject = preg_replace('#\(.*\<name\>[^)]+\)#', 'name', $subject);
echo $subject; 

Outputs :

/test/name/(?<id>\d+)/

Upvotes: 1

Related Questions