How to use preg_replace function to match images and add links in PHP_PHP Tutorial

WBOY
Release: 2016-07-21 15:12:40
Original
745 people have browsed it

Introduction: preg_replace performs regular expression search and replacement. If you are simply matching strings, it is recommended to use str_replace(), because its execution efficiency is much higher.
mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])

Search the subject for a match of the pattern pattern and replace it with replacement. If limit is specified, only limit matches are replaced; if limit is omitted or has a value of -1, all matches are replaced.

Referring to what I said before, PHP uses preg_match_all to match the pictures in the article. The code for matching pictures and adding links is given below:

Copy code The code is as follows:

$con = file_get_contents("http://www .jb51.net/");
$pattern="/<[img|IMG].*?src=['|"](.*?(?:[.gif|.jpg|.png] ))['|"].*?[/]?>/";
$new_con = preg_replace($pattern,"$0",$ con);
echo $new_con;
?>

Explanation: $0 represents the matching content, $1 represents the matching content of the first (), $2 represents the matching content of the second (), and so on!
This will add a link to the picture. Friends who are interested may wish to test it themselves.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326644.htmlTechArticleIntroduction: preg_replace performs regular expression search and replacement. If you are simply matching strings, it is recommended to use str_replace() , because its execution efficiency is much higher. mixed preg_replace...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!