note 73435 deleted from function.strip-tags by danbrown

From: Date: Sun, 17 May 2009 15:57:06 +0000
Subject: note 73435 deleted from function.strip-tags by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154722@lists.php.net to get a copy of this message
Note Submitter: lucky760 at yahoo dot com ---- I needed a way to allow user comments to contain only hyperlinks as the only allowed HTML tags. This is easy enough to accomplish, but I also needed a way to convert full URLs into hyperlinks, and this complicated things a bit. The functions below are not very elegant, but do the job. Function strip_tags_except() works similarly to the strip_selected_tags() function defined a few times on this page, but instead of allowing the user to specify the tags to strip, she can specify the tags to allow and strip all others. The third parameter, $strip, when TRUE removes "<" and ">" from the string and when FALSE converts them to "&lt;" and "&gt;" respectively. Function url_to_link() simply converts full URLs into an equivalent hyperlink taking into consideration that users may end a URL with a character that's not actually part of the address. When using both, url_to_link() should be called before strip_tags_except(). Here's an example as we are using it on http://www.VideoSift.com: <?php $summary = url_to_link($summary); $summary = strip_tags_except($summary, array('a'), FALSE); ?> Here are the function definitions: <?php function strip_tags_except($text, $allowed_tags, $strip=TRUE) { if (!is_array($allowed_tags)) return $text; if (!count($allowed_tags)) return $text; $open = $strip ? '' : '&lt;'; $close = $strip ? '' : '&gt;'; preg_match_all('!<\s*(/)?\s*([a-zA-Z]+)[^>]*>!', $text, $all_tags); array_shift($all_tags); $slashes = $all_tags[0]; $all_tags = $all_tags[1]; foreach ($all_tags as $i => $tag) { if (in_array($tag, $allowed_tags)) continue; $text = preg_replace('!<(\s*' . $slashes[$i] . '\s*' . $tag . '[^>]*)>!', $open . '$1' . $close, $text); } return $text; } function url_to_link($text) { $text = preg_replace('!(^|([^\'"]\s*))' . '([hf][tps]{2,4}:\/\/[^\s<>"\'()]{4,})!mi', '$2<a href="$3">$3</a>', $text); $text = preg_replace('!<a href="([^"]+)[\.:,\]]">!', '<a href="$1">', $text); $text = preg_replace('!([\.:,\]])</a>!', '</a>$1', $text); return $text; } ?>

« previous php.notes (#154722) next »