Volomike
Volomike

Reputation: 24886

RegExp for Markdown to BBCode (Simplistic)

Suppose I have a Markdown string:

* Bullet has *bold [code]*test[/code] part*. *Another\nbold* item.

And I want to convert it to BBCode like:

* Bullet has [b]bold [code]*test[/code] part[/b]. [b]Another\nbold[/b] item.

...and, as you can tell above, preserve what was inside [code]. How would I accomplish this?

BACKGROUND

See, I'm trying to tweak a FluxBB forum. It permits BBCode by default. However, I wanted to also permit a small subset of Markdown for noobs, such as bolding and italics. At least for bolding, this is possible with a statement like:

$out = preg_replace('/\*(\S.*?\S)\*/s','[b]$1[/b]',$in);

...but has a problem with the *test part, where it wants to translate that too.

Upvotes: 1

Views: 410

Answers (1)

Volomike
Volomike

Reputation: 24886

The following code seems to work. I preserve using a preg_replace_callback() and bin2hex(), and then unhex via pack() through another preg_replace_callback().

$a = "* Bullet\n* Bullet has *bold [code]*test[/code] part*. *Another\nbold* item.";
echo $a;
echo "\n";
// PRESERVE CODE BLOCK
$a = preg_replace_callback('/\[code\](.*?)\[\/code\]/s',create_function('$a','return "[code]" . bin2hex($a[1]) . "[/code]";'),$a);
// HANDLE MARKDOWN FOR BOLD
$a = preg_replace('/\*(\S.*?\S)\*/s','[b]$1[/b]',$a);
// RESTORE CODE BLOCK
$a = preg_replace_callback('/\[code\](.*?)\[\/code\]/s',create_function('$a','return "[code]" . pack("H*",$a[1]) . "[/code]";'),$a);
echo $a;
echo "\n";

Upvotes: 2

Related Questions