0

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

Maddy
  • 3
  • 1
  • 2
    Possible duplicate of [php url explode](https://stackoverflow.com/questions/15118047/php-url-explode) –  Mar 20 '19 at 22:03

2 Answers2

0

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

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

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Hi Nick, Thank you for the reply... it indeed work. Can you also help me with this url as well "$url = "http://localhost/Sub/index.php?a1=key/key-XYZ-1234.php";" with same reply. Thanks in advance – Maddy Mar 22 '19 at 06:46
  • @Maddy that's a bit trickier... what parts of `index.php?a1=key/key-XYZ-1234.php` do you want to keep? – Nick Mar 22 '19 at 06:59
  • Key, XYZ, 1234 only – Maddy Mar 22 '19 at 09:04
  • @Maddy I think changing the `$path` definition to `$path = parse_url($url, PHP_URL_PATH) . parse_url($url, PHP_URL_QUERY);` should work – Nick Mar 22 '19 at 11:04
  • Thanks Nick, your code worked as desired... you are the saver ... :) appreciate your help. – Maddy Mar 22 '19 at 11:23
  • @Maddy no worries. Glad to help. – Nick Mar 22 '19 at 11:24