简体   繁体   中英

How do I select a certain part of a string in PHP?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM