Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
Try parse_url – hakre Jul 28 '11 at 9:07

4 Answers

up vote 2 down vote accepted

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"
}
share|improve this answer

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
share|improve this answer

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
)
share|improve this answer

Don't use regex for this, see parse_url.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.