我正在尝试测试url是否会导致图像,例如"http://i.imgur.com/vLsht.jpg"通过测试查看字符串是否包含".jpg"、".png"或".gif"等
我的当前代码是:
if (stripos($row_rsjustpost['link'], ".png") !== false) {
//do stuff
}
我想做一些类似的事情
if (stripos($row_rsjustpost['link'], ".png" || ".jpg" || ".gif") !== false) {
//do stuff
}
这是通过preg_match()
:使用正则表达式的好方法
$matches = array();
if (preg_match('/'.(png|jpg|gif)/i', $row_rsjustpost['link'], $matches) {
// Contains one or more of them...
}
// $matches holds the matched extension if one was found.
print_r($matches);
注意:如果字符串必须像文件扩展名一样出现在末尾,请使用$
:终止它
/'.(png|jpg|gif)$/i
//-------------^^
如果您试图只定位一个子字符串,那么使用stripos()
会更合适,但您可以用正则表达式匹配许多不同的模式,而不必写出一个长的If/else链。
如果我不想使用正则表达式,我会这样做:
获取最后4个字符(文件扩展名)
$filepath = $row_rsjustpost['link'];
$extension = substr($filepath, length($filepath) - 4);
然后看看它是否匹配一个模式:
if (in_array($extension, array(".png", ".jpg", ".gif"))) {
// Have a party!
}