views:

56

answers:

3

To be honest, I suck at regex so much, I would use RegexBuddy, but I'm working on my Mac and sometimes it doesn't help much (for me).

Well, for what I need to do is a function in php

function replaceTags($n)
{
    $n = str_replace("[[", "<b>", $n);
    $n = str_replace("]]", "</b>", $n);
}

Although this is a bad example in case someone didn't close the tag by using ]] or [[, anyway, could you help with regex of:

[[ ]] = Bold format

** ** = Italic format

(( )) = h2 heading

Those are all I need, thanks :)

P.S - Is there any software like RegexBuddy available for Mac (Snow Leopard)?

+1  A: 
function replaceTags($n)
{
    $n = preg_replace("/\[\[(.*?)\]\]/", "<strong>$1</strong>", $n);
    $n = preg_replace("/\*\*(.*?)\*\*/", "<em>$1</em>", $n);
    $n = preg_replace("/\(\((.*?)\)\)/", "<h2>$1</h2>", $n);
    return $n;
}

I should probably provide a little explanation: Each special character is preceded by a backslash so it's not treated as regex instructions ("[", "(", etc.). The "(.*?)" captures all characters between your delimiters ("[[" and "]]", etc.). What's captured is then output in the replacements string in place of "$1".

Matt S
You might want to change the `.*` inside the match to the non-greedy `.*?` so that `[[bold]] not bold [[bold]]` won't result in `<strong>bold]] not bold [[bold</strong>`
gnarf
Excellent point. So edited.
Matt S
+1  A: 

The same reason you can't do this with str_replace() applies to preg_replace() as well. Tag-pair style parsing requires a lexer/parser if you want to yield 100% accuracy and cover for input errors.

Regular expressions can't handle unclosed tags, nested tags, that sort of thing.

That all being said, you can get 50% of the way there with very little effort.

$test = "this is [[some]] test [[content for **you** to try, ((does [[it]])) **work?";

echo convertTags( $test );

// only handles validly formatted, non-nested input
function convertTags( $content )
{
  return preg_replace(
      array(
          "/\[\[(.*?)\]\]/"
        , "/\*\*(.*?)\*\*/"
        , "/\(\((.*?)\)\)/"
      )
    , array(
          "<strong>$1</strong>"
        , "<em>$1</em>"
        , "<h2>$1</h2>"
      )
    , $content
  );
}
Peter Bailey
A: 

Modifiers could help too :)

http://lv.php.net/manual/en/reference.pcre.pattern.modifiers.php

U (PCRE_UNGREEDY) This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by ?. It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).

Anpher