-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.

1
  • parse_url to get the query string ("get" string), parse_str to parse it to an array. Check if the value isset and change it then http_build_query to change the array back into a query string and then append it after the ?. Commented Aug 29, 2016 at 20:32

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

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"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.