HOME       >>       Programming

A Simple Preg_replace Help Please.


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;?>



VIEW DESKTOP VERSION REGISTERGET FREE HOSTING

Xisto.com offers Free Web Hosting to its Members for their participation in this Community. We moderate all content posted here but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 2001-2019 by Xisto Corporation. All Rights Reserved.