php regular expressions

They have: 28 posts

Joined: May 2003

OK the code below acts like bbcode and does this link.
Could someone rewrite this where it would accept both the above and something like this --->> nameoflink

<?php
$bodytext
= preg_replace(\"`\[url\](?:=http://)?(.*?)\[/url\]`\", '<a href=\"http://\1\">[url]http://\1[/url]</a>', $bodytext);
?>

They have: 28 posts

Joined: May 2003

WTF, the code above didn't come out the way i wanted...hehehe I can even edit my posts on these boards Sad ahhhhh...rofl, how do I post the url tag w/o it actually using it. I'm going to use a star for the mean time...lol

OK the code below acts like bbcode and does this [*url]link[*/url]

Could someone rewrite this where it would accept both the above and something like this --->> [*url=myurl]nameoflink[*/url]

<?php
$bodytext
= preg_replace(\"`\[url\](?:=http://)?(.*?)\[/url\]`\", '<a href=\"http://\1\">[url]http://\1[/url]</a>', $bodytext);
?>

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

try this:

$bodytext = preg_replace('#\[url\](http://|ftp://|mailto:)?(.*?)\[/url\]#ie',
"'<a href=\"'.('\\1'==''?'http://':'\\1').'\\2\" target=\"_blank\">'.('\\1'==''?'http://':'\\1').'\\2</a>'",
$bodytext);
$bodytext = preg_replace('#\[url=("|\')?(http://|ftp://|mailto:)?(.*?)(?(1)\1)\](.*?)\[/url\]#ie',
"'<a href=\"'.('\\2'==''?'http://':'\\2').'\\3\" target=\"_blank\">\\4</a>'",
$bodytext);
'
test: http://host.maxalbert.com/testing_center/regex_exercise7.php
code: http://host.maxalbert.com/testing_center/phps_files/regex_exercise7.phps

Mark Hensler
If there is no answer on Google, then there is no question.

They have: 461 posts

Joined: Jul 2003

php.net. you can search functions

They have: 28 posts

Joined: May 2003

@ Mark Hensler

Thank you so much, that worked just fine. Except you had a typo
Changes made in RED
$bodytext = preg_replace('#\[url=("|\ ')?(<a href="http://" class="bb-url">http://</a>|<a href="ftp://" class="bb-url">ftp://</a>|mailto:)?(.*?)(?(1)\1)\](.*?)\[/url\]#ie','

the reason for the late reply is b/c I didn't receive an email notification...i dont' know why.

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

The forum software (for some unknown reason) has been forwarding me a lot of undeliverable mails as of late. So, I know quite a few subscription emails aren't getting sent. I intend to upgrade to vB3 once it goes stable, so we'll finally be rid of all these vB2 bugs.

Speaking of vB2 bugs... my code was fine (check the phps file linked above), but vB2 has a problem with escaped characters in code or php tags. For some reason, it doesn't escape the escape characters. Yet another quirk I've hated about vB2.

Glad you've got it working!

Mark Hensler
If there is no answer on Google, then there is no question.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.