2012-01-05 41 views
0

如何檢查給定的URL是否至少與一個網站名稱匹配?PHP的正則表達式來檢查匹配給定的URL

我:

$url_to_match = 'http://sub.somesite.com/'; 

我想說 「MATCH找到」 輸入開始時只http://sub.somesite.com

任何幫助將非常感激。

回答

2

使用PHP的parse_url()

$url = 'http://sub.somesite.com/'; 
if ('sub.somesite.com' === parse_url($url, PHP_URL_HOST)) { 
    // we have a match 
} 
+0

+1爲正確的工具。取決於OP是否也想驗證該方案。 – cmbuckley 2012-01-05 17:45:06

+0

非常感謝,做得很好。我很困惑與正則表達式的方法:)但這更簡單。 – swan 2012-01-05 17:55:10

0

我想你需要告訴我們你在做什麼,因爲這個請求沒有設計意義。

但是,要回答這個問題。

if(strpos($url_to_match, 'http://sub.anothersite.com/bla') !== FALSE) print 'bad string'; 
+0

這是strpos錯誤使用()(語法錯誤),但肯定的基礎上,這個問題,你需要使用strpos(),在這裏閱讀http://lt.php.net/strpos – 2012-01-05 17:40:49

+0

@AurelijusValeiša,很好,我不能相信我忘了'$乾草堆'。 XD – Xeoncross 2012-01-05 17:42:13

+0

我澄清了我的問題。我害怕做相反的事情並不是我的意思。感謝 – swan 2012-01-05 17:42:20

1

使用parse_url

例如:

function match_url($base,$input) 
{ 
    $base_host = parse_url($base,PHP_URL_HOST); 
    $input_host = parse_url($input,PHP_URL_HOST); 
    if($base_host === $input_host) { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 
$base_url = 'http://sub.somesite.com'; 
$input_url = 'http://sub.somesite.com//bla/bla'; 
echo (match_url($base_url,$input_url)) ? "URL matched" : "URL mismatched"; 
+0

謝謝,這也應該工作。 – swan 2012-01-05 17:56:08