DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Check A String For HTML

08.11.2011
| 2965 views |
  • submit to reddit
        <?php
// Function works on Both HTML, and XHTML
function is_html($str,$count = FALSE){
    $html = array('A','ABBR','ACRONYM','ADDRESS','APPLET','AREA','B','BASE','BASEFONT','BDO','BIG','BLOCKQUOTE','BODY','BR','BUTTON','CAPTION','CENTER','CITE','CODE','COL','COLGROUP','DD','DEL','DFN','DIR','DIV','DL','DT','EM','FIELDSET','FONT','FORM','FRAME','FRAMESET','H1','H2','H3','H4','H5','H6','HEAD','HR','HTML','I','IFRAME','IMG','INPUT','INS','ISINDEX','KBD','LABEL','LEGEND','LI','LINK','MAP','MENU','META','NOFRAMES','NOSCRIPT','OBJECT','OL','OPTGROUP','OPTION','P','PARAM','PRE','Q','S','SAMP','SCRIPT','SELECT','SMALL','SPAN','STRIKE','STRONG','STYLE','SUB','SUP','TABLE','TBODY','TD','TEXTAREA','TFOOT','TH','THEAD','TITLE','TR','TT','U','UL','VAR');
    if(preg_match_all("~(<\/?)\b(".implode('|',$html).")\b([^>]*>)~i",$str,$c)){
        if($count)
            return array(TRUE, count($c[0]));
        else
            return TRUE;
    }else{
        return FALSE;
    }
}

$str = 'This is my <span>string</span>';

// Version 1
// This version does not tell how many times HTML was added
if(is_html($str)){
    echo 'This contains HTML'; 
}else{
    echo 'This doesn\'t contain HTML';
}
    <a href="http://www.popularflashgames.tumblr.com">Popular Flash Games </a>
//Version 2
// This version will tell you how many times HTML was found
$str = 'This is a <span>cat</span>';
$a = is_html($str,TRUE);
if($a[0]){
    echo 'This contains HTML<br />';
    echo $a[1]; 
}else{
    echo 'This doesn\'t contain HTML';
}
?>