首页 > 开发 > PHP > 正文

php 获取文章内容的第一张图片示例

2024-05-04 22:00:06
字体:大 中 小
来源:转载
供稿:网友

php 获取文章内容的第一张图片方法非常的简单,我们最常用的是使用了正则了,下面与小伙伴一起来看看吧.

以下是关于选取文章中第一张图片的代码:

  1. $obj=M("News"); 
  2. $info=$obj->where('id=1')->find(); 
  3. //方法1********* 
  4. $soContent = $info['content']; 
  5. $soImages = '~<img [^>]* />~'; 
  6. preg_match_all( $soImages, $soContent, $thePics ); 
  7. $allPics = count($thePics[0]); 
  8. preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$thePics[0][0],$match); //开源软件:Vevb.com 
  9. dump($thePics); 
  10. if( $allPics> 0 ){ 
  11.     echo "<img src='".$match[1]."' title='".$match[1]."'>";//获取的图片名称 
  12. } 
  13. else { 
  14.     echo "没有图片"; 
  15. } 
  16. //************** 
  17. $soContent = $info['content']; 
  18. $soImages = '~<img [^>]* />~'; 
  19. preg_match_all( $soImages, $soContent, $thePics ); 
  20. $allPics = count($thePics[0]); 
  21. dump($thePics); 
  22. if( $allPics> 0 ){ 
  23.     echo $thePics[0][0]; //获取的整个Img属性 
  24. } else { 
  25.     echo "没有图片"; 
  26. } 
  27. //************** 
  28. $soImages = '~<img [^>]* />~'; 
  29. $str=$info['content']; 
  30. preg_match_all($soImages,$str,$ereg);//正则表达式把图片的整个都获取出来了 
  31. $img=$ereg[0][0];//图片 
  32. $p="#src=('|\")(.*)('|\")#isU";//正则表达式 
  33. preg_match_all ($p, $img, $img1); 
  34.    $img_path =$img1[2][0];//获取第一张图片路径 
  35. if(!$img_path){ 
  36.     $img_path="images/nopic.jpg"; 
  37. } //如果新闻中不存在图片,用默认的nopic.jpg替换 */ 
  38. echo $img_path; 
  39. //*************88 
  40. $str=$info['content']; 
  41. preg_match_all("/<img.*\>/isU",$str,$ereg);//正则表达式把图片的整个都获取出来了 
  42. $img=$ereg[0][0];//图片 
  43. $p="#src=('|\")(.*)('|\")#isU";//正则表达式 
  44. preg_match_all ($p, $img, $img1); 
  45.    $img_path =$img1[2][0];//获取第一张图片路径 
  46. if(!$img_path){ 
  47.     $img_path="images/nopic.jpg"; 
  48. } //如果新闻中不存在图片,用默认的nopic.jpg替换 */ 
  49. echo $img_path;

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表