...

View Full Version : Parsing Links Like phpBB



GSimpson
05-10-2009, 06:28 AM
Hey there,

I've recently taken a run at parsing links using php. I can't quite work out how to do it, so I'll just post what I'm trying to accomplish.

I have entries within a database, that include text and html. I've got that selected as $content.

I'm trying to get a function or set of functions to take this, and replace this:



<a href="http://myblog.com/">My Blog!</a>


with



[ url=http://myblog.com/]My Blog![ /url]


I just need to work out how to parse the link from within href="" and move it to after [url= then close it with ]. After that take what was within the anchor tags and put it between the [ url=] and [ /url] tags.

An ideas, or help?

Thanks everyone, Greatly appreciated.

Please ignore the spacing on the bb code, it was so that it would display on the forum.

thesavior
05-10-2009, 06:57 AM
This should do what you asked. The preg functions are the right stuff to be using, and regex is always good to learn.


preg_replace("/<a href=\"(.*?)">(.*?)</a>/", "[ url=$1]$2[ /url]", $content);

(remove the whitespace in the url tags of course.

GSimpson
05-10-2009, 07:25 AM
Thanks for that.

I'm just going to take a shot in the dark, and hope it's right, but, is this how I could reverse it, for the database entry?

(Assuming $content is the BB version, and we want to make it html)


preg_replace("/[ url=(.*?)](.*?)[/ url]/", "<a href=\"$1\">$2</a>", $content);

Thanks. :)

thesavior
05-10-2009, 07:59 AM
Close, on the regex side, you have to escape chars like [ and ] and / so it would be:


preg_replace("/\[ url=(.*?)\](.*?)\[\/ url\]/", "<a href=\"$1\">$2</a>", $content);

GSimpson
05-10-2009, 08:04 AM
Hey thanks for that, I'll be sure to have a read up of it soon.

I noticed on your first code your posted, it was missing \ before a quote so I added it in and then I got this message:

Warning: preg_replace() [function.preg-replace]: Unknown modifier 'a' in C:\Docum...

I was using this code (minus the url whitespaces)


preg_replace("/<a href=\"(.*?)\">(.*?)</a>/", "[ url=$1]$2[ /url]", $content);

thesavior
05-10-2009, 09:24 AM
oh, you probably have to escape the < and > as well, I just did it off the top of my head.

GSimpson
05-10-2009, 09:44 AM
Thanks man, I did a bit of research, and found some answers on how the syntax works. This is going to help me a lot in future. Thank you so much. :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum