【发布时间】:2012-02-23 23:20:38
【问题描述】:
我有一个输入框,告诉用户输入来自 imgur.com 的链接 我想要一个脚本来检查指定站点的链接,但我不知道该怎么做?
链接如下:http://i.imgur.com/He9hD.jpg 请注意,在 / 之后,文本可能会有所不同,例如不是 jpg,但主域始终是 http://i.imgur.com/。
任何帮助表示赞赏。 谢谢,乔希。(新手)
【问题讨论】:
我有一个输入框,告诉用户输入来自 imgur.com 的链接 我想要一个脚本来检查指定站点的链接,但我不知道该怎么做?
链接如下:http://i.imgur.com/He9hD.jpg 请注意,在 / 之后,文本可能会有所不同,例如不是 jpg,但主域始终是 http://i.imgur.com/。
任何帮助表示赞赏。 谢谢,乔希。(新手)
【问题讨论】:
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
}
【讨论】:
parse_url() 可能会失败,因此您需要在检查$input['host']之前确保它!== false
substr($input, 0, strlen('http://i.imgur.com/')) === 'http://i.imgur.com/'
【讨论】:
检查这个,使用stripos
if(stripos(trim($url), "http://i.imgur.com")===0){
// the link is from 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 )
...
【讨论】:
!== FALSE 或== 0。我会选择后者,因为您希望它作为字符串的开头。
=== 0。编辑:刚刚意识到你可能意味着抛出错误的条件。无视我。
有几种方法。这是一种:
if ('http://i.imgur.com/' == substr($link, 0, 19)) {
...
}
【讨论】: