从PHP字符串中获取值

时间:2018-07-28 19:57:17

标签: php

我的PHP脚本中有一个名为$url的变量

这是我的用法示例:

<?php 
$url = '/test/?utm_source=test&utm_campaign=test2&utm_medium=test3";

我希望有一个PHP代码段,可以捕获utm_sourceutm_campaignutm_medium的值。我该如何实现?

3 个答案:

答案 0 :(得分:1)

尝试一下

<?php 

$url = "/test/?utm_source=test&utm_campaign=test2&utm_medium=test3";

$url_parsed=parse_url($url);
$query_params=[];
$query_parsed=parse_str($url_parsed['query'],$query_params);

echo $query_params['utm_source'].PHP_EOL.
    $query_params['utm_campaign'].PHP_EOL.
    $query_params['utm_medium'].PHP_EOL;
?>

答案 1 :(得分:1)

具有爆炸功能的另一种方法:

<?php 
$url = "/test/?utm_source=test&utm_campaign=test2&utm_medium=test3";
$params = explode("=", $url);

$utmSource = explode("&", $params[1]);
$utmCampaign = explode("&", $params[2]);
$utmMedium = $params[3];

答案 2 :(得分:0)

我觉得函数parse_str()正是您要寻找的。参见https://secure.php.net/manual/en/function.parse-str.php