这是两个可以正常工作的功能,经过我的测试。
function isImage($url) {
if (substr($url, 0, 7) == 'http://') {
$i = str_ireplace('http://', '', $url); // delete first part
$i = explode('/', $i); // divide link into parts
$end = end($i); // get the last part
$ex = explode('.', $end); // get the extension if exists so for 'image.jpg' $ex = jpg
if (count($ex) === 2) {
$allowed = array('jpg', 'jpeg', 'png', 'gif'); // allowed image extensions
foreach ($allowed as $a) {
if ($ex = $a) {
# Is an image
return true;
}
}
} else {
# It's an url
return false;
}
} else {
# It's not even a link
return false;
}
}
function isLink($url) {
if (substr($url, 0, 7) == 'http://') {
$i = str_ireplace('http://', '', $url); // delete first part
$i = explode('/', $url); // divide link into parts
$end = end($i); // get the last part
$ex = explode('.', $end); // get the extension if exists so for 'image.jpg' $ex = jpg
return (count($ex) == 0) ? true : false;
} else {
# It's not even a link
return false;
}
}
$image = isImage($input); // true
$link = isLink($input); // false
var_dump($image, $link);
示例 (isLink()):
- 'google.com' = false (*)
- 'http://google.com' = true
- 'http://google.com/image.png' = 假
示例 (isImage()):
- 'google.com' = 假
- 'google.com/image.png' = false (*)
- 'http://google.com/image.png' = true
- 'http://google.com/view/model/controller' = false
(*) = 这是因为它检查链接是否有 http:// 作为前缀。如果你不希望这种情况发生,那么下面是函数:
function isImage($url) {
$i = explode('/', $i); // divide link into parts
$end = end($i); // get the last part
$ex = explode('.', $end); // get the extension if exists so for 'image.jpg' $ex = jpg
if (count($ex) === 2) {
$allowed = array('jpg', 'jpeg', 'png', 'gif'); // allowed image extensions
foreach ($allowed as $a) {
if ($ex = $a) {
# Is an image
return true;
}
}
} else {
# It's an url
return false;
}
}
function isLink($url) {
$i = explode('/', $url); // divide link into parts
$end = end($i); // get the last part
$ex = explode('.', $end); // get the extension if exists so for 'image.jpg' $ex = jpg
return (count($ex) == 0) ? true : false;
}
然后您可以将其用作:
if (isLink($url)) { echo "<a href=\"$url\">$url</a>"; }
if (isImage($url)) { echo "<img src=\"$url\" alt=\"image\">"; }