I recently required a PHP function that could strip a string of all HTML tags in a given list. Since PHP 4 we have had a function similar to this, strip_tags, but this works the other way. That is strip_tags will remove all HTML tags from a string except those given in the $allowable_tags parameter, but say I just wanted to strip all hyperlinks from a given string, I would have to list every other HTML tag if I was using strip_tags.

To solve the problem I wrote this quick function strip_html_tags that includes a binary flag that indicates whether the list of tags are those that should be removed or those that are allowed. If it is the latter, the function sensibly falls back to strip_tags.

define ('DO_STRIP', 1);
define ('DONT_STRIP', 0);

/* string strip_hmtl_tags(string $str [, int $flag = DONT_STRIP, string $tags = ''])
 */
function strip_hmtl_tags($string,$flag=DONT_STRIP,$tags=''){
    $tags = explode(',',$tags);
    if($flag === DONT_STRIP){
	    foreach($tags as $tag)
	      $angledtags .= '<'.$tag.'>';
        return strip_tags($string, $angledtags);
	}
	elseif($flag === DO_STRIP){
      if(empty($tags))
        return $string;
	  $pattern = '/<(';
	  foreach($tags as $tag)
	    $pattern .= $tag.'|';
	  $pattern = substr($pattern,0,-1);
	  $pattern .= ')[^>]*>([\s\S]*?)<\/\\1[^>]*>/';
      $diff = true;
      while($diff){
        $prev = $string;
	    $string = preg_replace($pattern, '$2', $string);
        $diff = $prev !== $string;
      }
      return $string; 
	}
    $caller = array_shift(debug_backtrace());
    trigger_error('Unknown flag supplied to strip_hmtl_tags in '.$caller['file'].' on line '.$caller['line'].'. Error triggered ', E_USER_ERROR);
	return $string;
}

$res = strip_hmtl_tags('<p>This <strong>is</strong> some <em>sample</em> text</p>', DO_STRIP, 'p,strong');
echo htmlspecialchars($res); //This is some <em>sample</em> text

The function takes the string in question, the binary flag, and a comma separated list of tag names. I post the function here in the hope others might find it useful.