'str_replace or preg_replace random number from string

I have a url from where i am fetching value using GET method and i want to replace that value with the 4 digit random number in the string like

This is my main URL: http://localhost/ab/index.php?id=3345

These are the strings in my table (fetching from database):

http://anyurl/index.php?id=4876&abc=any
http://anyurl/index.php?id=8726&abc=any
http://anyurl/index.php?id=9026&abc=any

So whenever i open the main url the id's of the table should be replaced according to the main url



Solution 1:[1]

you can get the id parameter using global GET variable

$id = $_GET["id"]

then you can change the urls in the table according to it

$url = "http://anyurl/index.php?id=".$id."&abc=any"

Hope this will help you

Solution 2:[2]

If you want to replace the id with preg_replace in string then you can do like below:

<?php
$string = 'http://anyurl/index.php?id=4876&abc=any';
$new_string = preg_replace('/[0-9]+/', $_GET["id"], $string);
echo $new_string;
// Will display http://anyurl/index.php?id=3345&abc=any 
?>

Solution 3:[3]

I know that it was asked years ago, but, probably, someone will find my solution helpful

So, I also offer to use preg_replace(), as Amit Gupta, but improve it for cases when you could have other numbers before ID value:

$url     = 'http://anyurl/index.php?foo=0713&id=4876&abc=any';
$new_id  = $_GET['id'];
// regex: catch 1 or more digits after 'id='
$new_url = preg_replace( '/id=(\d+)/', $new_id, $url );

If $_GET['id'] is 4920, for example, $new_url will be equal to http://anyurl/index.php?foo=0713&id=4920&abc=any

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shan pramuditha
Solution 2 Amit Gupta
Solution 3 burlakvo