我有以下函数可以返回帖子的第一张图片:
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',
$post->post_content, $matches);
但是返回任何图像,我需要忽略 gif 格式的图像,如何在正则表达式中添加此条件?
我有以下函数可以返回帖子的第一张图片:
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',
$post->post_content, $matches);
但是返回任何图像,我需要忽略 gif 格式的图像,如何在正则表达式中添加此条件?
更容易循环遍历结果并使用不同的正则表达式。
$output = preg_match_all('/<img[^>]+?src=[\'"](.+?)[\'"].*?>/i', $post->post_content, $matches);
foreach ($matches as $imgSrc)
{
if (!preg_match("/\.gif$/i"), $imgSrc)
{
$noGif[] = $imgSrc;
}
}
更容易理解,不会出现挡住文件名中恰好有字母“gif”的有效图片等意想不到的副作用。
注意,使用.+
and时要非常小心.*
。就目前而言,您的正则表达式比您想象的要匹配很多:
试试这个,例如:
<img whatever> whatever <img src="mypic.png"> <some other tag>
您可能不应该使用正则表达式
假设您有一个 HTML 文件,您正在尝试从标签中提取 URL。
<img src="http://example.com/whatever.jpg">
所以你写了一个这样的正则表达式(在 Perl 中):
if ( $html =~ /<img src="(.+)"/ ) {
$url = $1;
}
在这种情况下, $url 确实会包含http://example.com/whatever.jpg。但是当你开始获取这样的 HTML 时会发生什么:
<img src='http://example.com/whatever.jpg'>
或者
<img src=http://example.com/whatever.jpg>
或者
<img border=0 src="http://example.com/whatever.jpg">
或者
<img
src="http://example.com/whatever.jpg">
或者你开始得到误报
<!-- <img src="http://example.com/outdated.png"> -->
<img[^>]+src=[\'"](?:([^\'"](?!\.gif))+)[\'"][^>]*>
更新为只有一个捕获。
固定包括点。现在只会在像 a.gif.jpg 这样奇怪的事情上失败
还按照评论中的建议添加了安全匹配。