Welcome Guest ( Log In | Register)



 
Reply to this topicStart new topic
> A Simple Preg_replace Help Please.
apple
post Jun 25 2008, 11:38 PM
Post #1


Newbie [Level 2]
**

Group: Members
Posts: 31
Joined: 9-August 06
Member No.: 28,049



Hello..
Im looking for some help.

I want to use preg_replace function to replace the following type of code tags.
CODE
<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.
Go to the top of the page
 
+Quote Post
truefusion
post Jun 26 2008, 03:55 AM
Post #2


Ephesians 6:10-17
Group Icon

Group: [MODERATOR]
Posts: 1,917
Joined: 22-June 05
From: The World of Gentoo
Member No.: 8,528



You would need preg_replace_callback() instead.

Here's an example code to get you started:
CODE
<?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;

?>
Go to the top of the page
 
+Quote Post
gogoily
post Aug 4 2008, 09:06 AM
Post #3


Member [Level 3]
******

Group: Members
Posts: 99
Joined: 30-October 05
Member No.: 13,571



truefusion may make a mistake in 18th line, try this:
CODE
<?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;

?>
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic

Collapse

> Similar Topics

Topics Topics
  1. Regexp Function Preg_match_all()(0)
  2. Replace A Character In A Specific Tag(7)
  3. Help With Preg_replace(3)
  4. Preg_replace Problems(7)
  5. Validation Script - Detecting Illegal Characters(0)
  6. Php Preg Replace(1)
  7. Preg Replace Problem(1)


 



- Lo-Fi Version Time is now: 12th October 2008 - 05:52 AM