1

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);
3
  • Its a regex to see if it is a url. @anubhava Commented Mar 3, 2018 at 16:34
  • This question seems unclear to me. Do your input strings contain named capture groups? and you are trying to match regex patterns? What is the coding intent/logic here? What is the desired final result? I don't get it. Commented Mar 5, 2018 at 2:12
  • @mixmackusa Actually this is a route "/test/(?<name>\w+)/(?<id>\d+)/" that i used in a RouteCollectton class which i want to replace regex groups to generate url like this. /test/{name}/{id} So this regex function preg_replace('#(.*\<name\>[^)]+)#', 'name', $subject); convert route arguments to real url with provided parameters e.g. /test/name/54 the solution is below Commented Mar 5, 2018 at 10:52

1 Answer 1

1

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+)/
Sign up to request clarification or add additional context in comments.

1 Comment

Yes it works fine ! This is the pattern for id ([^)]+\<id\>[^)]+). i added to same pattern to beginning of the regex to prevent replacement of (?<name>\w+). Many Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.