Preg_replace Replace Content middle section

Source: Internet
Author: User
The requirement is this: match the image address in a tag in an HTML file with a regular

The initial implementation:

$img = "; $newImg = preg_replace ('//i '," ', $img); Echo $newImg;

Although this is not a problem, but does not conform to my original idea, my idea is to replace only the SRC content, retaining the left and right side of the label and attributes.

Look at the manual, the second parameter in Preg_replace () has this description:

Replacement can include a back reference \\n or (PHP 4.0.4 or more) $n, which is syntactically preferred. each such reference will be matched to the text that is captured by the nth capturing subgroup to replace . n can be 0-99,\\0 and $ A to represent the complete pattern matching text. The ordinal count of the capturing subgroup is: The opening parenthesis representing the capturing subgroup is left to right, starting at 1.

"Translating" into a rookie language is a regular expression in which each group can be replaced with \\n or $n in this parameter

OK, a small transformation of the program can meet the needs of

$img = "; $newImg = Preg_replace ('/()/', ' $1aaa.jpg$3 ', $img); Echo $newImg;

Will

Bbb.jpg could have been used to express, but here we need to replace, so directly with the aaa.jpg replacement is OK;

"style=" ... "..." > Divided into Group 3, with 1

Done

In the manual also said such a question, if our aaa.jpg to rename to 1.jpg then replacement becomes $11.jpg$3, group 1 name produced ambiguity, method is changed to ${1}1.jpg${3}, so in practical applications, whether it will produce ambiguity , plus the braces are more rigorous.

The above describes the Preg_replace replacement content in the middle section, including aspects of the content, I hope to be interested in PHP tutorial friends helpful.

  • 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.