php USES the preg_replace function to match images and link them

  • 2020-05-30 19:41:44
  • OfStack

Description: preg_replace performs regular expression search and replacement, and it is recommended to use str_replace() if it is simply a matching string, because it is much more efficient.
mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit])

Search 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 its value is -1, all matches are replaced.

As mentioned before, php matches the image in the article with preg_match_all. The code to match the image and add the link is given below:


<?php
$con = file_get_contents("https://www.ofstack.com/");
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
$new_con = preg_replace($pattern,"<a href='$1'>$0</a>",$con);
echo $new_con;
?> 

Description: $0 means the match content, $1 means the first () match content, $2 means the second () match content, and so on!
Add link to picture so, the friend that is interested in might as well test with one's own hands next.


Related articles: