tags:

views:

75

answers:

4

I have a url, http://www.jdocy.com/click-42343-32422

I want to replace the 42343 section of the url with php's preg_replace function.

How would I go about doing this?

A: 
$rep = '\1' + addslashes(111111) + '-\3';
$url = preg_replace('#(/)([\d]+)-([\d]+)#', $rep, $url);

Where 111111 is what you want to add. Addslashes is necessary to prevent accidentally including a backreference (\1, \2, \3)...

Edit: Fix missing quote

ircmaxell
Just watch the missing quote.
erisco
A: 
$url = preg_replace('`(?<=\.com/click-)\d+`i', 'replacement text', $url);

Use a look-behind and you don't need to re-insert any text.

Mark
whoops, i just realized the link is of the form "http://www.jdocy.com/click-42343-32422" , how can I modify your code to fit this form instead?
albert
add `click-` after the `.com` (see edit).
Mark
+1  A: 

Do you want to transform www.jdocy.com/42343-32422 to www.jdocy.com/32422? If so, you would use backreferences, something like:

 $url = preg_replace('/^(.+/)[0-9]+-([0-9]+)$/', '$1$2', $url)
ChrisV
A: 
$url = preg_replace('/^(.+/)[0-9]+-([0-9]+)$/', '$1$2', $url)

[spam edited out]

sunshine