Edit: the best I could come up with is
Code: Select all
$txt = trim($_POST["txt"]); // message text
$pat = array(); $rep = array();
$pat[0] = '/((http|https|ftp|mailto|steam):\/\/\S*?)(\s|$)/i'; // find URLs with protocols
$rep[0] = '[url]$1[/url]$3';
$pat[1] = '/(www\.\S*?)(\s|$)/i'; // find URL's starting with "www."
$rep[1] = '[url]http://$1[/url]$2';
//
$pat[2] = '/<(\/?[buis])>/i'; // allowed tags: <b>, <u>, <i>, <s>
$rep[2] = '[$1]';
$pat[3] = '/<(\/?code)>/i'; // allowed tag: <code>
$rep[3] = 'Code: Select all
';
$txt = strip_tags( preg_replace( $pat, $rep, $txt ) );
$tags = array( "url", "b", "u", "i", "s", "code" );
foreach( $tags as $tag ){
// if more tags of one kind are opened then closed,
// append the missing closing tags in the very end
while( substr_count( $txt, "[$tag]" ) > substr_count( $txt, "[/$tag]" ) ){
$txt.= "[/$tag]";
}
}
$txt = mysql_real_escape_string( htmlspecialchars( $txt ) ); // final precautions before sending off to SQL