2

I grab the URI string with php code. The URI could be:

solution 1 - http://www.site.com/one/two/
OR
solution 2 - http://www.site.com/one/two/var_abcdefg.html
OR
solution 3 - http://www.site.com/one/two/var_abcdefg.html?var=123456
OR
solution 4 - http://www.site.com/one/two/?var=123456

I would like to split the string in:

solution 1:
var 1 = "http://www.site.com/one/two/";
var 2 = "";
var 3 = "";
solution 2:
var 1 = "http://www.site.com/one/two/";
var 2 = "var_abcdefg.html";
var 3 = "";
solution 3:
var 1 = "http://www.site.com/one/two/";
var 2 = "var_abcdefg.html";
var 3 = "?var=123456";
solution 4:
var 1 = "http://www.site.com/one/two/";
var 2 = "";
var 3 = "?var=123456";

How I Can make it?

1
  • Try parse_url Commented Jul 28, 2011 at 9:07

3 Answers 3

3

There is faster way:

parse_url

$input  = 'http://www.site.com/one/two/var_abcdefg.html?var=123456';
$output = parse_url($input);

array(4) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(12) "www.site.com"
  ["path"]=>
  string(25) "/one/two/var_abcdefg.html"
  ["query"]=>
  string(10) "var=123456"
}
Sign up to request clarification or add additional context in comments.

Comments

2

No need of regex, PHP has a built-in function that breaks a url into parts : parse_url()

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

The above example will output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

Comments

2

If you really want to use RegEx instead of parse_url(), you could try this:

$url = 'http://www.site.com/one/two/var_abcdefg.html?var=123456';

preg_match('#^([^?]*?)([^/?]*)(\?.*|)$#', $url, $match);

$var_1 = $match[1]; // http://www.site.com/one/two/
$var_2 = $match[2]; // var_abcdefg.html
$var_3 = $match[3]; // ?var=123456

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.