Prevent urls from breaking layout

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
leenoble_uk
Forum Contributor
Posts: 108
Joined: Fri May 03, 2002 10:33 am
Location: Cheshire
Contact:

Prevent urls from breaking layout

Post by leenoble_uk »

In order to minimise the effect of people posting urls within page content which has the potential to massacre your page layout, this little snippet cuts off all of the url beyond the domain name (for display only) and also lets the resulting link text wrap wherever it finds a dot.

Sure it's not foolproof, a very long domain name could still screw you over but you could always pick a few other letters to be replaced using the soft-dot-method employed here.

Code: Select all

<?php
function create_soft_dots($input)
{
	$output = str_replace(".",".<span style="display: none"> </span>",$input);
	return $output;
}

$search = array("'(([^=])((https?://(([a-z0-9_-]{1,}\.[a-z0-9_\.-]+)/?)?[a-z0-9_/\+&#=\.-]*)))\b'i"
,"'\[url link=(((https?://([a-z0-9_-]{1,}\.[a-z0-9_\.-]+)/?)?[a-z0-9_/=\?&#;\.\+-]*))\]([a-z0-9&#;_\?= ''"\.@-]+)\[/url\]'ei"
);
$replace = array("\\2[url link=\\3]\\6[/url]"
	,"'<a href="\\1"'.(("\\3")?' target="_blank"':'').'>'.create_soft_dots("\\5").'</a>'"
);

$html = preg_replace($search, $replace, $plainText);
?>
This could be done with one regular expression but I've taken it from a piece of code which allows users to type BBCode type links within their text so the first expression it searches for is a plain url which is not immediately following an equals sign as this would be indicitive that it was within BBCode. It replaces these urls with BBCode style [url] links which are then searched for again and replaced with html links.
I'd also already stripped out html and replaced all special characters with their html encoded version before reaching this line.
Post Reply