Dragen Posted February 19, 2008 Share Posted February 19, 2008 Hi, I'm writing a very simple bbcode script. The problem I've got is with urls. I can easily turn this into a link: [url=somelink.com]this is a link[/url] But I'm having difficulty in insuring the the link starts with http(s):// Here's what I'm using: <?php function replace($text){ $patterns[] = '(\[b\](.+?)\[\/b\])'; $patterns[] = '(\[i\](.+?)\[\/i\])'; $patterns[] = '(\[sup\](.+?)\[\/sup\])'; $patterns[] = '(\[url\]([ a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#]*)\[\/url\])'; $patterns[] = '(\[url\=([ a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#]*)\](.+?)\[/url\])'; $reps[] = '<strong>$1</strong>'; $reps[] = '<em>$1</em>'; $reps[] = '<sup>$1</sup>'; $reps[] = '<a href="$1" target="_blank" title="$1">$1</a>'; $reps[] = '<a href="$1" target="_blank" title="$2">$2</a>'; return preg_replace($patterns, $reps, nl2br($text)); ?> I know there must be a simple way of checking and if needs be, adding the http://. Maybe I'm just too tired and being stupid. Quote Link to comment Share on other sites More sharing options...
Dragen Posted February 19, 2008 Author Share Posted February 19, 2008 okay, I've come up with a solution that works to a degree, but I'm not too keen on: function replace($text){ $patterns[] = '(\[url\](https?://)?([ a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#]*)\[\/url\])'; $patterns[] = '(\[url\=(https?://)?([ a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#]*)\](.+?)\[/url\])'; $reps[] = '<a href="http://$2" target="_blank" title="$2">$2</a>'; $reps[] = '<a href="http://$2" target="_blank" title="$3">$3</a>'; return preg_replace($patterns, $reps, nl2br($text)); } I just remove the http(s):// from the url (if it exists), then add http:// to the url, so url's which didn't have it now do. The problem is, if the url started with https I've now replaced it with http, which may cause problems. I'd prefer a method of checking if it has http(s)://. If so then leave it in the url, if not add http://. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.