-5

I have a URL as a string in $url.

I want to replace a specific parameter (if it exists) in the URL.

For example

$url = "http://www.xxx.xxx?data=1234324&id=abc&user=walter";

I'd like check if id exists and if it does, I want to replace the value of that id to a specific value. But the value of the id isn't always the same and it's not always in the same place.

Sherif
  • 11,786
  • 3
  • 32
  • 57
pfMusk
  • 769
  • 1
  • 7
  • 16
  • [parse_url](https://php.net/parse_url) to get the query string ("get" string), [parse_str](https://php.net/parse_str) to parse it to an array. Check if the value [isset](https://php.net/isset) and change it then [http_build_query](https://php.net/http_build_query) to change the array back into a query string and then append it after the `?`. – Jonathan Kuhn Aug 29 '16 at 20:32

1 Answers1

3

You can extract your query with PHP's parse_url function:

$b = parse_url($url, PHP_URL_QUERY);

From here you can use parse_str to get an associative array:

parse_str($b, $arr);

Now you can access the parameters

$arr['data'];
$arr['id'];
$arr['user'];

If you want to check if the id parameter exists you can use

if (isset($arr['id'])) {
//Do something
}
Daniel
  • 10,641
  • 12
  • 47
  • 85
  • and can you explain how i get the $url with the replaced id? and how i replace the array id? :D sorry im new in arrays ( and PHP ;) for example i want to replace the value of the id from "abc" to "xyz" – pfMusk Aug 29 '16 at 21:19