Jump to content

bbcode url, check http://


Dragen

Recommended Posts

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.

Link to comment
Share on other sites

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://.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.