0

I have a regex that takes a string like a bbcode and transforms it to a html link. It work fine. but, I want to make it detect the type of the link (internal/external) to decide whether to strictly use the absolute (external) url like http://extsite.com/category/keyword/ or use the part of the internal url like category/keyword/ and append it to a predefined url like $url . category/keyword/

The regex is as follows:

preg_replace('/\[([^\]]+)\]\[([^\]"]+)\]/i', '<a href="$2">$1</a>', $text)

Any suggestion will be very appreciated.

1
  • 1
    how do you define an internal link? is it any link that doesn't start with http:// ? Commented Apr 28, 2012 at 9:49

1 Answer 1

1

Based on your comment, I will assume that any link that starts with http:// (or any similar protocol, e.g. ftp://) is an absolute link. Any other link will be considered a relative link (and will be prefixed by $url)

// replace absolute links
$text = preg replace ('/\[([^\]]+)\]\[([A-Za-z]+:\/\/[^\]"]+)\]/i',
                      '<a href="$2">$1</a>', $text )


// replace all remaining (relative) links
// $url must have a tailing slash '/'
$text = preg replace ('/\[([^\]]+)\]\[([^\]"]+)\]/i',
                      '<a href="'.$url.'$2">$1</a>', $text )
Sign up to request clarification or add additional context in comments.

3 Comments

ok I have already done it but with https? instead of [A-Za-z]+ but your example seems to be better as mine doesn't support protocols other than http and https. thanks.
How about the // relative protocol? It still counts as an external link //google.com is a valid external URL.
@Truth: the regexp can be modified as such. As I said, it depends on the definition of "external" and "internal" links

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.