简体   繁体   English

如何在PHP中选择字符串的特定部分?

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

I have an array of URLs. 我有一个网址数组。 The URLs look similar to: URL看起来类似于:

https://maps.googleapis.com/maps/api/place/details/json?placeid= $place_id&key=myAPIkey 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. $place_id是一个在每个网址中都会更改的变量。 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. 因此,当我遍历URL时,我希望它提取正在使用的URL的那一部分,并将其分配给我可以在代码中使用的变量( $place )。 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. 我已经看过strpos()和/或substr() ,但是我不知道如何使用它们,因为$place_id每次$place_id改变。 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. 我认为$place_id的长度始终是相同的,但是我不是100%肯定,因此最好使用适合不同长度的解决方案。

Alternatively, I am already have the multiple $place_ids in an array. 另外,我已经在数组中有多个$ place_ids。 I am generating the array of URLs by using 我正在通过使用生成URL数组

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. 如果有一种方法,我可以通过某种检查或使用它们在数组中的位置来确保$place_id的值与URL的值一致。

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() . 由于您在此处处理URL,因此您可能希望使用PHP的内置帮助器parse_url()parse_str()

For example, you can separate the GET parameters with parse_url and then extract each argument into an array with parse_str: 例如,您可以将GET参数与parse_url分开,然后使用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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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