Replace the content with a regular expression in php and a regular expression in php.

Source: Internet
Author: User

Replace the content with a regular expression in php and a regular expression in php.

A previous project involves a Q & A page, for example, inserting an expression in the answer or question content. The name of the emoticon image (without a suffix, for example, f_002.png) is written in the content and placed in the project, I need to replace the emoticon name with the image when removing the content.

The content stored in the database is as follows: I don't know [f_013] (the last [f_013] is the form of the emoticon stored in the database)

What I need to do is retrieve the content from the database and process the character [f_013] like this in the content into an image address. It is clear that a regular expression is needed here.

1. First, I need to find this string

$rule = "/(?:\[)(f_.[0-9]{1,3})(?:\])/i";

This regular expression matching can help me find the expression string

2. Replace the string with the address of the emoticon image. Here, a function is used to replace the regular expression.

This is the function: preg_match_all

echo preg_replace("/(?:\[)(f_.[0-9]{1,3})(?:\])/i","
$ Line ['content'] This is the content I extracted from the database,
"
There is a very important knowledge point: "\ $ {1}" it is the character string that stores the expressions in the database.
\ $ {1} = f_013

Here is a complete code I replaced:
<? Php
$ Result = array (); $ n = preg_match_all ("/(? : \ [) (F _. [0-9] {1, 3 })(? : \])/I ", $ line ['content'], $ result ); /* returns the number of matching strings */if ($ n = 0 | $ n = false) /* if it is 0 or false, it indicates no expression */
{Echo $ line ['content'];} else
{Echo preg_replace ("/(? : \ [) (F _. [0-9] {1, 3 })(? : \])/I "," ", $ line ['content']) ;}?>

 

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.