通过PHP拆分URL

问题描述 投票:0回答:2

嗨,我是PHP的新手,对于我的家庭项目,我需要帮助,我想在URL中拆分值。

$url = "http://localhost/Sub/Key/Key_XYZ_1234.php";

网址也可以是:

$url = "http://localhost/Sub/Key/Key-XYZ-1234.php";

键值可以是“ABC-TT”或“ABC_TT”或只是“ABC”

预期结果$v1 = value of Key; $v2 = value of XYZ; $v3 = value of 1234;

提前致谢

php preg-replace preg-match
2个回答
0
投票

你可以用parse_urlbasenamepreg_split的组合来做到这一点。我们使用preg_split所以我们可以处理分隔符是-_

$url = "http://localhost/Sub/Key/Key-XYZ-1234.php";
$path = parse_url($url, PHP_URL_PATH);
$file = basename($path, '.php');
list($v1, $v2, $v3) = preg_split('/[-_]/', $file);
echo "\$v1 = $v1\n\$v2 = $v2\n\$v3 = $v3\n";

输出:

$v1 = Key 
$v2 = XYZ 
$v3 = 1234

Demo on 3v4l.org


0
投票

就像是....

//this is psuedo code, but you can look up the function names to see how to use them

$path=parse_url($url, PHP_URL_PATH);
$sep="-";
if(strpos($path,$sep)===false){
   $sep="_";
}
$pieces=explode($sep,$path);
$key=$pieces[0];
$a=$pieces[1];
$nums=$peices[2];
© www.soinside.com 2019 - 2024. All rights reserved.