I have an array of URLs. The URLs look similar to:
https://maps.googleapis.com/maps/api/place/details/json?placeid=$place_id&key=myAPIkey
The $place_id is a variable that changes in every single url.
I want to be able to select just this part of the url.
So when I loop through the URLs, I want it to extract that part, of the URL I am using, and assign it to a variable ($place) that I can use in my code. I have looked at strpos() and / or substr(), but I don't know how I would use them since the $place_id changes every time. I think the length of $place_id is always the same, but I am not 100% certain so a solution that worked for different lengths would be preferable.
Alternatively, I am already have the multiple $place_ids in an array. I am generating the array of URLs by using
foreach ($place_ids as $place_id) {
array_push(
$urls,
"https://maps.googleapis.com/maps/api/place/details/json?placeid=$place_id&key=myAPIkey"
);
}
I am then using
foreach ($urls as $url){}
to loop through this array. If there was a way I could check to make sure the value of $place_id coincided with the value of the URL either through some sort of check or by using their position in the array that would work too.
I'm sorry if any of this is incorrect and if there are any questions I can answer or ways for me to improve my question I'd be happy to.
Since you're dealing with URLs here, you'll probably want to use PHP's built-in helpers, parse_url() and parse_str().
For example, you can separate the GET parameters with parse_url and then extract each argument into an array with parse_str:
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=<arg1>&key=<arg2>';
$args = [];
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $args);
// args => ["placeid" => "<arg1>", "key" => "<arg2>"]
A regular expression will do
$match = array();
$url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=346758236546&key=myAPIkey";
preg_match('/[?&]placeid=([^&]+)(?:$|.*)/', $url, $match);
var_dump($match[1]); // string(12) "346758236546"
Related
I have got a large array of lets say 500 urls, now using array_unique I can remove any duplicate values. However I am wanting to remove any duplicate values where the domain is the same while keeping the original domain (so only removing duplicates so this value is now unique).
I have been using the following however this only removes duplicate values:
$directurls = array_unique($directurls);
I have been playing around with the following to get the domain but am wondering how I can check the entire array for other parse_url domains in the array:
foreach($directurls as $url) {
$parse = parse_url($url);
print $parse['host']; //the domain name I just need to find a way to check this and remove it
}
I imagine I will need to use some form of loop perhaps where I can get the current host and check all other hosts in the array. If duplicates remove all duplicates and keep the current value. Maybe something like this could work am just testing it now:
foreach($directurls as $url) {
$parse = parse_url($url);
if (in_array($parse['host'], $directurls)) {
//just looking for a way to remove while keeping unique
}
}
If anyone has any suggestions or recommendations on other ways to go about this I would be very thankful.
Let me know if I need to explain a bit more.
You could avoid having to loop through the URLs by using array_map() with a callback function.Grab the domain using parse_url(), and create a new array with just the domains. Now, you can simply create a new array with the URLs as keys and domains as values and just call array_unique() to get the unique items. Now, to get just the URLs into a new array, you can use array_keys():
$domains = array_map(function($d) {
$parts = parse_url($d); // or: parse_url($d)['host'] if PHP > 5.4
return $parts['host'];
}, $directurls);
$result = array_keys(array_unique(array_combine($directurls, $domains)));
Demo!
I am just wondering what the best way of extracting "parameters" from an URL would be, using PHP.
If I got the URL:
http://example.com/user/100
How can I get the user id (100) using PHP?
To be thorough, you'll want to start with parse_url().
$parts=parse_url("http://example.com/user/100");
That will give you an array with a handful of keys. The one you are looking for is path.
Split the path on / and take the last one.
$path_parts=explode('/', $parts['path']);
Your ID is now in $path_parts[count($path_parts)-1].
You can use parse_url(), i.e.:
$parts = parse_url("http://x.com/user/100");
$path_parts= explode('/', $parts[path]);
$user = $path_parts[2];
echo $user;
# 100
parse_url()
This function parses a URL and returns an associative array containing
any of the various components of the URL that are present. The values
of the array elements are not URL decoded.
This function is notmeant to validate the given URL, it only breaks it
up into the above listed parts. Partial URLs are also
accepted, parse_url() tries its best to parse them correctly.
$url = "http://example.com/user/100";
$parts = Explode('/', $url);
$id = $parts[count($parts) - 1];
I know this is an old thread but I think the following is a better answer:
basename(dirname(__FILE__))
I was wondering how I could remove a certain part of a url using PHP.
This is the exact url in questions:
http://www.mysite.com/link/go/370768/
I'm looking to remove the number ID into a variable.
Any help would be great, Thanks!
There are many (many!) ways of extracting a number from a string. Here's an example which assumes the URL starts with the format like http://www.mysite.com/link/go/<ID> and extracts the ID.
$url = 'http://www.mysite.com/link/go/370768/';
sscanf($url, 'http://www.mysite.com/link/go/%d', $id);
var_dump($id); // int(370768)
Use explode()
print_r(explode("/", $url));
You could use mod_rewrite inside of your .htaccess to internally rewrite this URL to something more friendly for PHP (convert /link/go/370768/ into ?link=370768, for example).
I suspect that you are using some kind of framework. There are two ways to check the $_GET variables:
print_r($_GET);
or check the manual of the manual of the framework and see how the GET/POST is passed internally, for example in CakePHP you have all parameters save internally in your controller you can access them like that:
$this->params['product_id'] or $this->params['pass']
There is another solution which is not very reliable and professional but might work:
$path = parse_url($url, PHP_URL_PATH);
$vars = explode('/', $path);
echo $vars[2];
$vars should contain array like this:
array (
0 => link
1 => go
2 => 370768
)
Can't wrap my head around this...
Say, we explode the whole thing like so:
$extract = explode('tra-la-la', $big_sourse);
Then we want to get a value at index 1:
$finish = $extract[1];
My question is how to get it in one go, to speak so. Something similar to this:
$finish = explode('tra-la-la', $big_sourse)[1]; // does not work
Something like the following would work like a charm:
$finish = end(explode('tra-la-la', $big_sourse));
// or
$finish = array_shift(explode('tra-la-la', $big_sourse));
But what if the value is sitting somewhere in the middle?
Function Array Dereferencing has been implemented in PHP 5.4. For older version that's a limitation in the PHP parser that was fixed in here, so no way around it for now I'm afraid.
Something like that :
end(array_slice(explode('tra-la-la', $big_sourse), 1, 1));
Though I don't think it's better/clearer/prettier than writing it on two lines.
you can use list:
list($first_element) = explode(',', $source);
[1] would actually be the second element in the array, not sure if you really meant that. if so, just add another variable to the list construct (and omit the first if preferred)
list($first_element, $second_elment) = explode(',', $source);
// or
list(, $second_element) = explode(',', $source);
My suggest - yes, I've figured out something -, would be to use an extra agrument allowed for the function. If it is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. So, if we want to get, say, a value at index 2 (of course, we're sure that the value we like would be there beforehand), we just do it as follows:
$finish = end(explode('tra-la-la', $big_sourse, 3));
explode will return an array that contains a maximum of three elements, so we 'end' to the last element which the one we looked for, indexed 2 - and we're done!
I have an URL
http://example.com/test?xyz=27373&page=4&test=5
which I want to tranform by replacing the page=4 through page=XYZ
how can I do that with preg_replace?
Yes, you can use
$oldurl = "http://test.com/test?xyz=27373&page=4&test=5"
$newurl = preg_replace("/page=\d+/", "page=XYZ", $oldurl);
Or you can reconstruct the URL from $_GET superglobal.
Do you want to set the value of xyz to the page value? I think you might need to specify a bit more. But this is easy to modify if you dont know regex.
$url = 'http://test.com/test?xyz=27373&page=4&test=5';
$urlQuery = parseUrl($url, PHP_URL_QUERY);
parse_str($urlQuery, $queryData);
$queryData['page'] = $queryData['xyz'];
unset($queryData['xyz']);
$query = http_build_query($queryData);
$outUrl = substr_replace($url, $query, strpos($url, '?'));
$url = 'http://test.com/test?xyz=27373&page=4&test=5';
preg_match('/xyz=([^&]+)/', $url, $newpage);
$new = preg_replace('/page=([^&]+)/', $newpage[0], $url);
$new = preg_replace('/xyz=([^&]+)&/', '', $new);
This will turn
http://test.com/test?xyz=27373&page=4&test=5
into
http://test.com/test?page=27373&test=5
Forgive me if this isn't what you were looking to do, but your question isn't quite clear.
I'm sure you could do something with a regular expression. However, if the URL you've given is the one you're currently handling, you already have all the request variables in $_Request.
So, rebuild the URL, replacing the values you want to replace, and then redirect to the new URL.
Otherwise, go find a regexp tutorial.
If this is your own page (and you are currently on that page) those variables will appear in a global variable named $_GET, and you could use something like array_slice, unset or array_filter to remove the unwanted variables and regenerate the URL.
If you just have that URL as a string, then what exactly are the criteria for removing the information? Technically there's no difference between
...?xyz=27373&page=4&test=5
and
...?test=5&xyz=27373&page=4
so just removing all but the first parameter might not be what you want.
If you want to remove everything except the xyz param. Take a look at parse_url and parse_str
What exactly are you trying to do? The question is a little unclear.
$XYZ = $_GET['xyz'];
$PAGE = $_GET['page'];
?
Are wanting to replace each value with another, or replace both with one?