Using the preg_replace function in php to match images and add links

Source: Internet
Author: User

Description: preg_replace: searches and replaces regular expressions. If you only want to match strings, we recommend that you use str_replace () because of its high execution efficiency.
Mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])

Search for matches in pattern in subject and replace them 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 above, php uses preg_match_all to match the image in the article. The following code matches the image and adds the link:

Copy codeThe Code is as follows: <? Php
$ Con = file_get_contents ("http://www.jb51.net /");
$ Pattern = "/<[img | IMG]. *? Src = [\ '| \ "] (. *? (? : [\. Gif | \. jpg | \. png]) [\ '| \ "]. *? [\/]?> /";
$ New_con = preg_replace ($ pattern, "<a href = '$ 1'> $0 </a>", $ con );
Echo $ new_con;
?>

Note: $0 indicates the Matching content. $1 indicates the content of the first () Match. $2 indicates the content of the second () match, and so on!
In this way, you can add a link to the image. If you are interested, try it yourself.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.