Honesty Rocks! truth rules.

A Simple Preg_replace Help Please.

HOME      >>       Programming

apple

Hello..
Im looking for some help.

I want to use preg_replace function to replace the following type of code tags.

<code lang="php"></code><code lang="javascript"></code><code lang="css"></code>

My question is that, in the above code tags, language (lang) is not always same, how can i use preg_replace with the above code tags to place them with something.

Any help will be very much appreciated.
thanks.

truefusion

You would need preg_replace_callback() instead.

Here's an example code to get you started:

<?php$str = '<code lang="php"></code><code lang="javascript"></code><code lang="css"></code>';function parse_code($matches){ if ($matches[1] == "php"){ return "[ code ]".$matches[2]."[ /code ]"; } else if ($matches[1] == "javascript"){ return "[ code ]".$matches[2]."[ /code ]"; } else if ($matches[1] == "css"){ return "[ code ]".$matches[2]."[ /code ]"; }}$str = preg_replace_callback("/<code lang=\"(\w+)\">(.*)<\/code>/", "parse_code", $str);echo $str;?>


gogoily

truefusion may make a mistake in 18th line, try this:

<?php$str = '<code lang="php"></code><code lang="javascript"></code><code lang="css"></code>';function parse_code($matches){ if ($matches[1] == "php"){ return "[ code ]".$matches[2]."[ /code ]"; } else if ($matches[1] == "javascript"){ return "[ code ]".$matches[2]."[ /code ]"; } else if ($matches[1] == "css"){ return "[ code ]".$matches[2]."[ /code ]"; }}$str = preg_replace_callback("/<code lang=\"(\w+)\">(.*)<\/code>/", "parse_code", $matches);echo $str;?>