Page 1 of 1

Parsing Tags, converting bracketed phrases into HREF links

Posted: Mon Feb 06, 2006 6:16 pm
by Saint3k
I am attempting to create a quick and dirty code parser for my personal wiki project, similar to how Wikipedia parses phrases that are surrounded by double brackets. I have looked at how Mediawiki parses, but thier method is far to complex for me to easilly understand. Basically, I'd like to use some sort of str_replace (or something similar) on a variable, have it look for phrases that begin with [[ and end with ]], and have it replace them with href links to a specific url.

Basically, I want to turn the following...

Code: Select all

Hello, my name is [[David]].
into...

Code: Select all

Hello, my name is <a href="url.php?entry=David">David</a>.
Unfortunately, I cannot figure out the proper way to parse the code. I have been looking at str_replace, but ereg_replace and preg_replace also look like possibilities. Can anyone help me out? I'm ussually pretty good with PHP, but when it comes to regular expressions I'm like a fish out of water.

Posted: Mon Feb 06, 2006 6:25 pm
by Christopher
You might want to look around for one of the many BBCode functions/classes.

Posted: Mon Feb 06, 2006 8:40 pm
by Saint3k
Thanks Arborint, with some careful searching I was able to find some easy BBCode strings and reverse engineer them to suit my purpose.

Here's what I ended up with...

Code: Select all

$description = preg_replace('`\[\[(.+?)\]\]`is', '<a href=wiki.php?entry=\\1>\\1</a>', $wiki_entry->description);
The only problem I'm having now is that if I have something like

Code: Select all

[[this is a test]]
, it will truncate it to just

Code: Select all

test
when it parses it. It seems to have problem with spaces. Is there an easy fix to that, possibly?

Posted: Mon Feb 06, 2006 8:48 pm
by s.dot
I don't really see why it's doing that, (.+?) should catch spaces I think

try replaceing a space with %20 would be my guess

Code: Select all

$description = preg_replace(" ", "%20", preg_replace('`\[\[(.+?)\]\]`is', '<a href=wiki.php?entry=\\1>\\1</a>', $wiki_entry->description));

Posted: Mon Feb 06, 2006 9:23 pm
by feyd
quoting your HREF would help..

Posted: Mon Feb 06, 2006 9:28 pm
by Saint3k
HA!

Okay, now I feel stupid. Thanks Feyd. :D