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']) ;}?>