Home > Article > Backend Development > PHP regular expression practice: matching image links
In the process of web development, we often need to extract image links from articles to display images or store them locally. At this time, regular expressions become an important tool. This article will introduce how to use PHP regular expressions to match image links, and conduct practical exercises through sample code.
1. Matching rules for image links
In highly complex and changeable web pages, the formats of image links vary. The following are some common image link formats:
f2c1e9d33d026e38180fdaa6edf6d2ca
203f1b65967aec8ac84e3c48ece3b17f
61ae07240d49718a1d70113176073298
b682d6e1e2cf77318fe25317f252bcfe
01a74d99e188719f4abbbac9ac3abf2f
9086b68fddc20f80999dfb7d0934f895
0f8d6d0e27a2bac8ad9a4ed2b3b86ca8
According to the above format, we can summarize a general matching rule, as follows:
/d16d7b9c80d03f543fa5f641226ead7e/i
Where, regular expression Some of the meanings are as follows:
2. Use PHP code to match image links
Next, we will use PHP to match image links.
The preg_match function is used to perform regular expression matching on a single string. The following is a PHP code for matching a single image link:
<?php $str = '<img src="../images/picture.jpg" class="picture" width="100" height="100">'; $pattern = '/<img.*?src=['"](.*?(?:gif|jpg|jpeg|bmp|png))['"].*?>/i'; preg_match($pattern, $str, $matches); echo $matches[1]; ?>
The output of the above code is:
../images/picture.jpg
The preg_match_all function is used to perform regular expression matching on a set of strings. The following is a PHP code for matching multiple image links:
<?php $str = ' <img src="../images/picture.jpg" class="picture" width="100" height="100"> <img src="http://www.example.com/images/picture.jpg"> <img src="http://www.example.com/images/picture.png"> <img src="http://www.example.com/images/picture.gif"> '; $pattern = '/<img.*?src=['"](.*?(?:gif|jpg|jpeg|bmp|png))['"].*?>/i'; preg_match_all($pattern, $str, $matches); print_r($matches[1]); ?>
The output of the above code is:
Array
(
[0] => ../images/picture.jpg [1] => http://www.example.com/images/picture.jpg [2] => http://www.example.com/images/picture.png [3] => http://www.example.com/images/picture.gif
)
3. Summary
This article introduces how to use PHP regular expressions to match image links, and provides sample code for practical exercises. In actual development, we can modify the matching rules of regular expressions as needed. At the same time, you can also use the matched image link for operations such as image display, downloading or storage.
The above is the detailed content of PHP regular expression practice: matching image links. For more information, please follow other related articles on the PHP Chinese website!