我有一個輸入框,告訴用戶輸入從imgur.com鏈接 我想要一個腳本來檢查鏈接是爲指定的網站,但我不是起訴如何做到這一點?刪除部分字符串與PHP
鏈接如下:http://i.imgur.com/He9hD.jpg 請注意,在/之後,文字可能會有所不同,例如:不是一個JPG,但主要領域總是http://i.imgur.com/。
任何幫助表示讚賞。 謝謝,喬希(新手)
我有一個輸入框,告訴用戶輸入從imgur.com鏈接 我想要一個腳本來檢查鏈接是爲指定的網站,但我不是起訴如何做到這一點?刪除部分字符串與PHP
鏈接如下:http://i.imgur.com/He9hD.jpg 請注意,在/之後,文字可能會有所不同,例如:不是一個JPG,但主要領域總是http://i.imgur.com/。
任何幫助表示讚賞。 謝謝,喬希(新手)
試試這個:
<?php
if(preg_match('#^http\:\/\/i\.imgur.com\/#', $_POST['url']))
echo 'Valid img!';
else
echo 'Img not valid...';
?>
其中$ _POST ['url']是用戶輸入。
我還沒有測試過這段代碼。
$url_input = $_POST['input_box_name'];
if (strpos($url_input, 'http://i.imgur.com/') !== 0)
...
substr($input, 0, strlen('http://i.imgur.com/')) === 'http://i.imgur.com/'
這樣做的幾種方法。這裏是一個:
if ('http://i.imgur.com/' == substr($link, 0, 19)) {
...
}
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
}
檢查這一點,使用stripos
if(stripos(trim($url), "http://i.imgur.com")===0){
// the link is from imgur.com
}
需要被'!== FALSE'或'== 0'。我會選擇後者,因爲你會預期它會成爲字符串的開始。 – simshaun 2012-02-23 23:25:30
!== FALSE不會給我們的位置檢查,只是存在之一。 )並且== 0是不正確的,因爲它對FALSE也有相同的響應。 – raina77ow 2012-02-23 23:31:27
我暗示了位置檢查,後者會更好。但是,你是對的,它需要'=== 0'。編輯:剛剛意識到你可能意味着拋出一個錯誤的條件。不理我。 – simshaun 2012-02-23 23:33:01