Preg_replace in PHP uses regular expressions to replace matches in the subject with the given replacement. The syntax of preg_replace is as follows:
[code lang=”php”]
preg_replace(pattern,replacement,subject [,limit]);
[/code]
A good example of using preg_replace is with simple bbcode and smilies. However with more complex bbcode there are other ways that would proove to be much easier and more useful. Let’s say you want to replace smiley code with the image of your smilies. Here is how you would do it with preg_replace:
[code lang=”php”]
$str = $_POST[“textbox”];
$smiliesFind = array(
‘/:\)/’,
‘/:P/’,
);
$smiliesReplace = array(
‘‘,
‘‘,
);
print preg_replace($bbcodeFind,$bbcodeReplace,$str);[/code]
This will take all of those matches in the input $_POST[‘textbox’] and replace it with the HTML code of the smiley’s image. Now, why does the find code use slashes like this?
When using regular expressions you need a syntax. The slashes provide that regular expression and the backslashes are needed to escape the parts that could be mistaken as something else in the preg_replace. This goes for anything you want to escape when executing php code.
We can use preg_replace for some bbcode as well:
[code lang=”php”]
$bbcodeFind = array(
‘/\[color\=(.*?)\](.*?)\[\/color\]/is’,
‘/\[b\](.*?)\[\/b\]/is’,
‘/\[i\](.*?)\[\/i\]/is’,
);
$bbcodeReplace = array(
‘$2‘,
‘$1‘,
‘$1‘,
);
print preg_replace($bbcodeFind,$bbcodeReplace,$str);
[/code]
You can see the use of “(.*?)” in the find array. This will apply the code to any text found inside the tags we supply. This is how it would appear:
Green text!
Bold text!
Italic text!