I've looked at every post on SO that remotely pertains to this and I just can't figure this out. This code is taken directly from another SO post and was marked as the correct working answer:
$query = $_GET;
// replace parameter(s)
$query['d'] = 'new_value';
// rebuild url
$query_result = http_build_query($query);
// new link
Link
Again, taken straight from another post. When I try this code, i change the $_GET to the actual URL that i want to alter. When the code gets to the $query['d'] part, it tells me I get an illegal string offset and the error is the index that's specified. So then I parse the URL, and then do parse_str($query, $output) which in turn allows me to do $output['d'] and THEN I can set a new value to that variable. If I echo it out, it's fine.
But then I get to the http_build_query line, and it tells me that it's expecting an array or object and I can't build the new URL. Here is my code:
$link = parse_url('https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=coding+tutorial', PHP_URL_QUERY);
parse_str($link, $output);
$output['oq'] = 'new value';
$query_result = http_build_query($link);
echo $query_result;
This code yields that the http_build_query function wants an array or object...i guess i'm not giving it that in some way? What do I need to do to get this to work?
If you want to rebuild the full URL after modifying the query parameters, you could do this:
$url = 'https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=coding+tutorial';
$link = parse_url($url, PHP_URL_QUERY);
parse_str($link, $output);
$output['oq'] = 'new value';
echo substr($url, 0, strpos($url, '?') + 1) . http_build_query($output);
Output:
https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=new+value
Related
lets say I have an url
http://www.somepage.com/clicker.php?id_campaign=8&id_email=9324&url=https://www.google.com/search?q=dog&sxsrf=ALeKk019eteEpAwVf2Fk4qYo7TiwhuMQ_Q:1596666153666&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiqzqf3jIXrAhUisaQKHRayBWAQ_AUoAXoECBkQAw&biw=1920&bih=921#imgrc=M4wsJO0A7OQfTM
and im trying to get out the parameters id_campaign, id_email and url
however, using the code:
$url = htmlspecialchars_decode($url);
$parts = parse_url($url);
parse_str($parts['query'], $query);
when printing $parts['query'] it only gives me:
https://www.google.com/search?q=dog
because rest of the url it consider as another parameter...
so how do I get all the url parameter out of $url?
In an ideal scenario, the URLs passed within the query would be URL-encoded, as opposed to HTML-encoded.
What you could do in your case is manually replace all & by something temporary and then replace them all back after parsing the URL. This is not exactly pretty, but works:
$url = str_replace('&', '__TEMP__', $url);
$parts = parse_url($url);
parse_str($parts['query'], $query);
$urlParam = str_replace('__TEMP__', '&', $query['url']);
echo $urlParam;
Demo
I'd like to find a clean if possibile (without too much string manipulation preg_*)
I know that to replace a parameter I would do
$_GET['info'] = "newinfo";
and to remove a parameter:
unset($_GET['info']);
so is there something like that that I can use?
of course after I've "unset" or "set" I'm building a new query.
(http_build_query).
At the end I'm trying to make this:
/index.php?foo=bar
to
/index.php?foo=bar&info=newinfo
Just do this:
$get = $_GET;
$get['new'] = 'some value';
function getPath()
{
// Stolen from https://stackoverflow.com/a/8775529/3578036
$request = parse_url($_SERVER['REQUEST_URI']);
$path = $request["path"];
return rtrim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $path), '/');
}
header("Location: " . getPage() . http_build_query($get));
The above code will create a query string and append it to the current URL and redirect to that location. Obviously, you can change the location that you redirect to by replacing the getPage() function result and putting your own result there, this just demonstrates the premise of the answer.
The docs for http_build_query are a very good place to start.
Effectively, what it will do is convert an associative array into an HTTP query string.
may not have explained this properly but here we go.
I have a URL that looks like http://www.test.co.uk/?page=2&area[]=thing&area[]=thing2
Multiple "area"s can be added or removed from the URL via links on the site. on each addition of n "area" I wanted to remove the "page" part of the URL. so it can be reset to page1. I used parse_url to take that bit out.
Then I built an http query so it could generate the URL properly without "page"
this resulted in "area%5B0%5D=" "area%5B1%5D=" instead of "area[]="
When I use urldecode, now it shows "area[0]=" and "area[1]="
I need it to be "[]" because when using a link to remove an area, it checks for the "[]=" - when it's [0] it doesn't recognise it. How do I keep it as "[]="?
See code below.
$currentURL = currentURL();
$parts = parse_url($currentURL);
parse_str($parts['query'], $query);
unset($query['page']);
$currenturlfinal = http_build_query($query);
urldecode($currenturlfinal);
$currentURL = "?" . urldecode($currenturlfinal);
This is what I've done so far - it fixes the visual part in the URL - however I don't think I've solved anything as I've realised that what represents 'area' and 'thing' is not recognised as $key or $val as a result of what I think is parsing or reencoding the url in accordance with the code below. So I still can't remove 'areas' using the links
$currentURL_with_QS2 = currentURL();
$parts = parse_url($currentURL_with_QS2);
parse_str($parts['query'], $query);
unset($query['page']);
$currenturlfinal = http_build_query($query);
$currenturlfinal = preg_replace('/%5B[0-9]+%5D/simU', '[]', $currenturlfinal);
urldecode($currenturlfinal);
$currentURL_with_QS = "?" . $currenturlfinal;
$numQueries = count(explode('&', $_SERVER['QUERY_STRING']));
$get = $_GET;
if (activeCat($val)) { // if this category is already set
$searchString = $key . '[]= ' . $val; // we build the query string to remove
I'm using Wordpress as well may I add - maybe there's a way to reset the pagination through Wordpress. of course even then - when I go to page 2 on any page it still changes the "[]" to "5b0%5d" etc....
EDIT: this is all part of a function that refers to $key (the area/category) and $val (name of area or category) which is echoed in the link itself
EDIT2: It works now!
I don't know why but I had to use the original code and make the adjustments I did before again and now it works exactly how I want it to! Yet I couldn't see any visible differences in both codes afterwards. Strange...
As far as I know, there is no built-in way to do this.
You could try with:
$currenturlfinal = http_build_query($query);
Where $query is querystring part w/o area parameters and then:
foreach ($areas as $area) {
$currenturlfinal .= '&area[]='.$area;
}
UPD:
you could try with:
$query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
just place it right after http_build_query call.
I am trying to set up a small script that can play youtube videos but thats kinda besides the point.
I have $ytlink which equals www.youtube.com/watch?v=3WAOxKOmR90
But I want to make it become www.youtube.com/embed/3WAOxKOmR90
Currently I have tried
$result = str_replace('https://youtube.com/watch?v=', "https://youtube.com/watch?v=", $ytlink);
But this returns it as standard
I have also tried
preg_replace('/https://youtube.com/watch?v=/, '/https://youtube.com/embed/', $ytlink);
but both of these dont work.
Instead of using ugly regexes, I recommend using parse_url() with parse_str(). This allows you to be flexible in the event that you want to change something or if Youtube decides to change their URL slightly.
$url = 'https://www.youtube.com/watch?v=3WAOxKOmR90';
// Parse the URL into parts
$parsed_url = parse_url($url);
// Get the whole query string
$query = $parsed_url['query'];
// Parse the query string into parts
parse_str($query, $params);
// Get the parameter you want
$v = $params['v'];
// Now re-build the URL how you want
echo $parsed_url['scheme'].'://'.$parsed_url['host'].'/embed/'.$v;
// Outputs: https://www.youtube.com/embed/3WAOxKOmR90
This works:
$ytlink = 'www.youtube.com/watch?v=3WAOxKOmR90';
$result = str_replace('watch?v=', 'embed/', $ytlink);
echo $result;
$url = 'www.youtube.com/watch?v=3WAOxKOmR90';
echo preg_replace('/.*?v=(\w+)/i', 'www.youtube.com/embed/$1', $url);
I am trying to grab the second argument of a URL such as this:
http://website.com/?p=2?id=ass92jdskdj92
I just want the id portion of the address. I use the following code to grab the first portion of the address:
$p = $_GET[p];
$remove = strrchr($p, '?');
$p = str_replace($remove, "", $p);
Any hints on how to get the second portion?
Arguments in links are started by ? and divided by &.
That means your link should look like this:
http://website.com/?p=2&id=ass92jdskdj92
And you get them by:
$p = $_GET['p'];
$id = $_GET['id'];
First change the URL
only first argument start with ? and rest of all is append by &
u should try with
echo parse_url($url, PHP_URL_PATH);
Reference:
parse url