Home >Backend Development >PHP Tutorial >php Get the first image example of article content_PHP tutorial
To use php to get the first picture among all the pictures in the article, we only need a simple regular expression. Let me share two examples with you.
First look at a function:
The code is as follows | Copy code | ||||
Preg_match_all("/ $img=$ereg[0][0];//Picture $p="#src=('|")(.*)('|")#isU";//regular expression Preg_match_all ($p, $img, $img1); $img_path =$img1[2][0];//Get the first image path Return $img_path; } //If the database is open, use $nr to get the news content in the database $nr=$row_news["nr"]; $aa=getpic($nr_a); if(!$aa){$aa="images/nopic.jpg";} //If there is no picture in the news, replace it with the default nopic.jpg |
Look at another function that is relatively complicated
When working on a project, the design of the page sometimes leaves a place for the image featured in the article. However, sometimes, the article does not upload the image, so when it is displayed on the page, there is no image, and the style is ugly. If there is no uploaded image and the default image is selected, sometimes it will cause some misunderstandings; then consider whether to refine the issue of images in this article first: first determine whether there are uploaded images, and if so, display the uploaded images. If there is no picture, it will be judged whether there is a picture in the content. If there is, the first picture will be selected as the featured picture here. If there is no picture in the content, the default picture will be displayed here;
The following is the code for selecting the first image in the article:
The code is as follows | Copy code |
$obj=M("News"); $soContent = $info['content']; //****************** $soContent = $info['content']; //****************** $soImages = '~]* />~'; //***************88 $str=$info['content']; |