This article mainly introduces the php method for obtaining the first image in the article, involving operations on regular expressions, which is of great practical value, for more information about how to use php to obtain the first image of an article, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
Using php to obtain the first image of an article is very simple. We use regular expressions most often. if you are interested, refer to the following code in the example.
The following code selects the first image in the document:
The code is as follows:
$ Obj = M ("News ");
$ Info = $ obj-> where ('Id = 1')-> find ();
// Method 1 *********
$ SoContent = $ info ['content'];
$ SoImages = '~] */> ~ ';
Preg_match_all ($ soImages, $ soContent, $ thePics );
$ AllPics = count ($ thePics [0]);
Preg_match ('// I', $ thePics [0] [0], $ match );
Dump ($ thePics );
If ($ allPics> 0 ){
Echo ""; // the image name.
}
Else {
Echo "no image ";
}
//**************
$ SoContent = $ info ['content'];
$ SoImages = '~] */> ~ ';
Preg_match_all ($ soImages, $ soContent, $ thePics );
$ AllPics = count ($ thePics [0]);
Dump ($ thePics );
If ($ allPics> 0 ){
Echo $ thePics [0] [0]; // Obtain the entire Img attribute
} Else {
Echo "no image ";
}
//**************
$ SoImages = '~] */> ~ ';
$ Str = $ info ['content'];
Preg_match_all ($ soImages, $ str, $ ereg); // the regular expression retrieves the entire image.
$ Img = $ ereg [0] [0]; // Picture
$ P = "# src = ('| \") (. *) (' | \ ") # isU"; // regular expression
Preg_match_all ($ p, $ img, $ img1 );
$ Img_path = $ img1 [2] [0]; // obtain the first image path
If (! $ Img_path ){
$ Img_path = "images/nopic.jpg ";
} // If no image exists in the news, replace it with your nopic.jpg */
Echo $ img_path;
// *************** 88
$ Str = $ info ['content'];
Preg_match_all ("// isU", $ str, $ ereg); // the regular expression retrieves the entire image.
$ Img = $ ereg [0] [0]; // Picture
$ P = "# src = ('| \") (. *) (' | \ ") # isU"; // regular expression
Preg_match_all ($ p, $ img, $ img1 );
$ Img_path = $ img1 [2] [0]; // obtain the first image path
If (! $ Img_path ){
$ Img_path = "images/nopic.jpg ";
} // If no image exists in the news, replace it with your nopic.jpg */
Echo $ img_path;
I hope this article will help you with PHP programming.