2012-02-23 89 views

回答

1

試試這個:

<?php 
if(preg_match('#^http\:\/\/i\.imgur.com\/#', $_POST['url'])) 
    echo 'Valid img!'; 
else 
    echo 'Img not valid...'; 
?> 

其中$ _POST ['url']是用戶輸入。

我還沒有測試過這段代碼。

1
$url_input = $_POST['input_box_name']; 
if (strpos($url_input, 'http://i.imgur.com/') !== 0) 

...

+0

需要被'!== FALSE'或'== 0'。我會選擇後者,因爲你會預期它會成爲字符串的開始。 – simshaun 2012-02-23 23:25:30

+0

!== FALSE不會給我們的位置檢查,只是存在之一。 )並且== 0是不正確的,因爲它對FALSE也有相同的響應。 – raina77ow 2012-02-23 23:31:27

+0

我暗示了位置檢查,後者會更好。但是,你是對的,它需要'=== 0'。編輯:剛剛意識到你可能意味着拋出一個錯誤的條件。不理我。 – simshaun 2012-02-23 23:33:01

2
substr($input, 0, strlen('http://i.imgur.com/')) === 'http://i.imgur.com/' 
1

這樣做的幾種方法。這裏是一個:

if ('http://i.imgur.com/' == substr($link, 0, 19)) { 
    ... 
} 
3

嘗試parse_url()

try { 
    if (!preg_match('/^(https?|ftp)://', $_POST['url']) AND !substr_count($_POST['url'], '://')) { 
     // Handle URLs that do not have a scheme 
     $url = sprintf("%s://%s", 'http', $_POST['url']); 
    } else { 
     $url = $_POST['url']; 
    } 

    $input = parse_url($url); 

    if (!$input OR !isset($input['host'])) { 
     // Either the parsing has failed, or the URL was not absolute 
     throw new Exception("Invalid URL"); 
    } elseif ($input['host'] != 'i.imgur.com') { 
     // The host does not match 
     throw new Exception("Invalid domain"); 
    } 

    // Prepend URL with scheme, e.g. http://domain.tld 
    $host = sprintf("%s://%s", $input['scheme'], $input['host']); 
} catch (Exception $e) { 
    // Handle error 
} 
+0

'parse_url()'可能會失敗,因此在檢查'$ input ['host']' – simshaun 2012-02-23 23:30:13

+0

@simshaun之前,您需要確保它'!== false'這是真的,但不是在「快速」答案中。我爲你增強了答案 – Cez 2012-02-23 23:31:42

+0

???快速回答與否,這是必要的,否則你在代碼中引入了一個潛在的錯誤。 – simshaun 2012-02-23 23:35:56

2

檢查這一點,使用stripos

if(stripos(trim($url), "http://i.imgur.com")===0){ 
// the link is from imgur.com 
}