我有一个输入框,告诉用户输入从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