用php获取字符串中的第一个图像 [英] Getting the first image in string with php
本文介绍了用php获取字符串中的第一个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正试图从我的每个帖子中获取第一张图片。如果我只有一个图像,下面这段代码很有效。但如果我有一个以上的它给了我一个图像,但并不总是第一个。
I'm trying to get the first image from each of my posts. This code below works great if I only have one image. But if I have more then one it gives me an image but not always the first.
我真的只想要第一张图片。很多时候第二张图片是下一个按钮
I really only want the first image. A lot of times the second image is a next button
$texthtml = 'Who is Sara Bareilles on Sing Off<br>
<img alt="Sara" title="Sara" src="475993565.jpg"/><br>
<img alt="Sara" title="Sara two" src="475993434343434.jpg"/><br>';
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $texthtml, $matches);
$first_img = $matches [1] [0];
现在我可以把这个$ first_img放在简短的描述前面
now I can take this "$first_img" and stick it in front of the short description
<img alt="Sara" title="Sara" src="<?php echo $first_img;?>"/>
推荐答案
如果您只需要第一个源标记, preg_match
应该代替 preg_match_all
,这对你有用吗?
If you only need the first source tag, preg_match
should do instead of preg_match_all
, does this work for you?
<?php
$texthtml = 'Who is Sara Bareilles on Sing Off<br>
<img alt="Sara" title="Sara" src="475993565.jpg"/><br>
<img alt="Sara" title="Sara two" src="475993434343434.jpg"/><br>';
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $texthtml, $image);
echo $image['src'];
?>
这篇关于用php获取字符串中的第一个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文