0

I'm trying to replace a number in a string with another number by using regex. This should be super simple, but for some reason it's giving me grief today. "feed" in the string is dynamic and can contain letters or numbers only.

Here is what I've tried:

$new_number = 999;
$string = '/feed/page/1/?param=true';
preg_replace('/\/([0-9a-z])\/page\/([0-9])\/(.*)/i', '/$1/page/'.$new_number.'/$3', $string);

Should output: '/feed/page/999/?param=true'

2
  • 1
    As a side note, you can use other characters than / to delimit regex. '@/([0-9a-z]+)/page/([0-9]+)/(.*)@i' is sexier than '/\/([0-9a-z]+)\/page\/([0-9]+)\/(.*)/i'. Commented Mar 11, 2013 at 2:09
  • Thanks @DoubleGras! I had no idea about that. Commented Mar 11, 2013 at 23:28

2 Answers 2

2

forgetting the +'s, are you? :P Try this as your regEx:

'/\/([0-9a-z]+)\/page\/([0-9]+)\/(.*)/i' 
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

\/([0-9a-z]{1,})\/page\/([0-9]{1,})\/(.*)

Comments

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.