這些是兩個功能正常工作,並由我測試。
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'=假(*)
- 'http://google.com'=真
- 的「http:// google.com/image.png」 =假
實例(isImage()
):
- 'google.com'=假
- 'google.com/image.png'=假(*)
- 'http://google.com/image.png'=真
- ' 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\">"; }
感謝,但考慮IM輸入文本包含一些鏈接和圖片,那我該如何改變它? – 2011-03-01 12:08:18
我更新了我的問題,也許這種呈現方式更好。 – 2011-03-01 12:12:01
更新了我的答案(請參閱最後3行)。 – Shoe 2011-03-01 13:08:09