Jump to content

Replace number in a URL...


Recommended Posts

I'm using "extract_unit" function in order to extract a URL. Now I want to change the first number (15) to 9.


(The URL name/number can vary (for example "http://nemo2.test.com..."))

I used the function: $unit = preg_replace('~(?:\A..|(?!\A)\G)[^0-9]*\K[0-9]+~', '9', $unit);
but it changes all the numbers.

Please can you help me with the regular expressions in order to change only the first number?

Thank you in advance.

Edited by Badchip
Link to comment
Share on other sites

Yes, two slashes are necessary, since one of them is to escape the backslash in the PHP string. If the page is blank that means the PHP syntax is incorrect, check your server's error log to find out why. It looks like I forgot delimiters around my regular expression, which you should have been able to identify on your own.

preg_replace('#[0-9]+\\.test\\.com#', '9.test.com', $unit);

Your expression selects any set of digits, that's why it's changing the whole URL. If you want to identify a particular set of digits then you need to find parts of the URL that are surrounding it.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...