Split URL by PHP

谁都会走 提交于 2019-12-11 19:03:05

问题


Hi I'm a newbie in PHP and for my home project I need help where I want to split values with in a URL.

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

url can also be:

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

key value can be "ABC-TT" or "ABC_TT" or just "ABC"

intended result $v1 = value of Key; $v2 = value of XYZ; $v3 = value of 1234;

Thanks in advance


回答1:


You can do this with a combination of parse_url, basename and preg_split. We use preg_split so we can deal with the separator being either a - or an _:

$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";

Output:

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

Demo on 3v4l.org




回答2:


Something like....

//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];


来源:https://stackoverflow.com/questions/55270823/split-url-by-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!