2012-02-23 88 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 
}