Jump to content
xisto Community
Sign in to follow this  
apple

A Simple Preg_replace Help Please.

Recommended Posts

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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.