开发者

PHP - Parse String with Regex

开发者 https://www.devze.com 2023-03-23 06:45 出处:网络
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

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 = "";
sol开发者_运维问答ution 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?


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"
}


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
)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消