2011-07-28 67 views
2

我用php代碼抓取URI字符串。 的URI可能是:PHP - 用正則表達式解析字符串

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 

我想拆分的字符串:

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

我如何能做到嗎?

+0

嘗試['parse_url'](http://php.net/manual/en/function.parse-url.php ) – hakre

回答

3

有更快的方式:

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

無需正則表達式,PHP有一個內置的功能,打破一個網址分成幾部分:parse_url()

<?php 
$url = 'http://username:[email protected]/path?arg=value#anchor'; 

print_r(parse_url($url)); 

echo parse_url($url, PHP_URL_PATH); 
?> 

上面的例子將輸出:

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

如果你真的想要,而不是使用正則表達式parse_url(),你可以試試這個:

$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 
相關問題