strip_tags

(PHP 4, PHP 5)

strip_tagsУдаляет HTML и PHP-теги из строки

Описание

string strip_tags ( string $str [, string $allowable_tags ] )

Эта функция пытается возвратить строку str, из которой удалены все NUL-байты, HTML и PHP теги. Для удаления тегов используется тот же автомат, что и в функции fgetss().

Список параметров

str

Входная строка.

allowable_tags

Второй необязательный параметр может быть использован для указания тегов, которые не нужно удалять.

Замечание:

Комментарии HTML и PHP-теги также будут удалены. Это жестко записано в коде и не может быть изменено с помощью параметра allowable_tags.

Замечание:

Этот параметр не должен содержать пробелов. strip_tags() рассматривает тег как нечувствительную к регистру строку, находящуюся между < и первым пробелом или >. Это означает, что strip_tags("<br/>", "<br>") вернет пустую строку.

Возвращаемые значения

Возвращает строку без тегов.

Список изменений

Версия Описание
5.0.0 strip_tags() теперь безопасна для обработки бинарных данных
4.3.0 Комментарии HTML теперь всегда удаляются

Примеры

Пример #1 Пример использования strip_tags()

<?php
$text 
'<p>Параграф.</p><!-- Комментарий --> <a href="#fragment">Еще текст</a>';
echo 
strip_tags($text);
echo 
"\n";

// Разрешаем <p> и <a>
echo strip_tags($text'<p><a>');
?>

Результат выполнения данного примера:

Параграф. Еще текст
<p>Параграф.</p> <a href="#fragment">Еще текст</a>

Примечания

Внимание

Из-за того, что strip_tags() не проверяет валидность HTML, то частичные или сломанные теги могут послужить удалением большего количества текста или данных, чем ожидалось.

Внимание

Эта функция не изменяет атрибуты тегов, разрешенных с помощью allowable_tags, включая такие атрибуты как style и onmouseover, которые могут быть использованы озорными пользователями при посылке текста, отображаемого также и другим пользователям.

Смотрите также

  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности

Коментарии

strip_tags has doesn't recognize that css within the style tags are not document text. To fix this do something similar to the following:

$htmlstring = preg_replace("'<style[^>]*>.*</style>'siU",'',$htmlstring);
2001-12-18 14:57:25
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Strip tags will NOT remove HTML entities such as &nbsp;
2002-03-15 00:19:13
http://php5.kiev.ua/manual/ru/function.strip-tags.html
strip_tags() appears to become nauseated at the site of a <!DOCTYPE> declaration (at least in PHP 4.3.1). You might want to do something like:

$html = str_replace('<!DOCTYPE','<DOCTYPE',$html);

before processing with strip_tags().
2003-09-10 16:03:39
http://php5.kiev.ua/manual/ru/function.strip-tags.html
it seems we're all overlooking a few things:
1) if we replace "</ta</tableble>" by removing </table, we're not better off. try using a char-by-char comparison, and replaceing stuff with *s, because then this ex would become "</ta******ble>", which is not problemmatic; also, with a char by char approach, you can skip whitespace, and kill stuff like "< table>"... just make sure <&bkspTable> doesn't work...
2) no browser treats { as <.[as far as i know]
3) because of statement 2, we can do:

<?php
$remove
=array("<?","<","?>",">");
$change=array("{[pre]}","{[","{/pre}","]}");
$repairSeek = array("{[pre]}""</pre>","{[b]}","{[/b]}","{[br]}");
// and so forth...

$repairChange("<pre>","</pre>","<b>","<b>","<br>");
// and so forth...

$maltags=array("{[","]}");
$nontags=array("{","}");
$unclean=...;//get variable from somewhere...
$unclean=str_replace($remove,$change,$unclean);
$unclean=str_replace($repairSeek$repairChange$unclean);
$clean=str_replace($maltags$nontags$unclean);

////end example....
?>

4) we can further improve the above by using explode(for our ease):

<?php
function purifyText($unclean$fixme)
{
$remove=array();
$remove=explode("\n",$fixit['remove']);
//... and so forth for each of the above arrays...
// or you could just pass the arrays..., or a giant string
//put above here...
return $clean
}//done
?>
2003-10-26 12:15:39
http://php5.kiev.ua/manual/ru/function.strip-tags.html
I am creating a rendering plugin for a CMS system (http://b2evolution.net) that wraps certain bits of text in acronym tags.  The problem is that if you have something like this:
<a href="http://www.php.net" title="PHP is cool!">PHP</a>

then the plugin will mangle it into:

<a href="http://www.<acronym title="PHP: Hypertext Processor">php</acronym>.net" title="<acronym title="PHP: Hypertext Processor">PHP</acronym> is cool!>PHP</a>

This function will strip out tags that occur within other tags.  Not super-useful in tons of situations, but it was an interesting puzzle.  I had started out using preg_replace, but it got riduculously complicated when there were linebreaks and multiple instances in the same tag.

The CMS does its XHTML validation before the content gets to the plugin, so we can be pretty sure that the content is well-formed, except for the tags inside of other tags.

<?php
if( !function_exists'antiTagInTag' ) )
{
   
// $content is the string to be anti-tagintagged, and $format sets the format of the internals.
   
function antiTagInTag$content ''$format 'htmlhead' )
    {
        if( !
function_exists'format_to_output' ) ) 
        {   
// Use the external function if it exists, or fall back on just strip_tags.
           
function format_to_output($content$format)
            {
                return 
strip_tags($content);
            }
        }
       
$contentwalker 0;
       
$length strlen$content );
       
$tagend = -1;
        for( 
$tagstart strpos$content'<'$tagend ) ; $tagstart !== false && $tagstart strlen$content ); $tagstart strpos$content'<'$tagend ) )
        {
           
// got the start of a tag.  Now find the proper end!
           
$walker $tagstart 1;
           
$open 1;
            while( 
$open != && $walker strlen$content ) )
            {
               
$nextopen strpos$content'<'$walker );
               
$nextclose strpos$content'>'$walker );
                if( 
$nextclose === false )
                {   
// ERROR! Open waka without close waka!
                    // echo '<code>Error in antiTagInTag - malformed tag!</code> ';
                   
return $content;
                }
                if( 
$nextopen === false || $nextopen $nextclose )
                { 
// No more opens, but there was a close; or, a close happens before the next open.
                    // walker goes to the close+1, and open decrements
                   
$open --;
                   
$walker $nextclose 1;
                }
                elseif( 
$nextopen $nextclose )
                { 
// an open before the next close
                   
$open ++;
                   
$walker $nextopen 1;
                }
            }
           
$tagend $walker;
            if( 
$tagend strlen$content ) ) 
               
$tagend strlen$content );
            else
            {
               
$tagend --;
               
$tagstart ++;
            }
           
$tag substr$content$tagstart$tagend $tagstart );
           
$tags[] = '<' $tag '>';
           
$newtag format_to_output$tag$format );
           
$newtags[] = '<' $newtag '>';
           
$newtag format_to_output$tag$format );
        }
       
       
$content str_replace($tags$newtags$content);
        return 
$content;
    }
}
?>
2004-08-16 02:16:38
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Be aware that tags constitute visual whitespace, so stripping may leave the resulting text looking misjoined.

For example, 

"<strong>This is a bit of text</strong><p />Followed by this bit"

are seperable paragraphs on a visual plane, but if simply stripped of tags will result in

"This is a bit of textFollowed by this bit"

which may not be what you want, e.g. if you are creating an excerpt for an RSS description field.

The workaround is to force whitespace prior to stripping, using something like this:

<?php
      $text 
getTheText();
     
$text preg_replace('/</',' <',$text);
     
$text preg_replace('/>/','> ',$text);
     
$desc html_entity_decode(strip_tags($text));
     
$desc preg_replace('/[\n\r\t]/',' ',$desc);
     
$desc preg_replace('/  /',' ',$desc);
?>
2004-08-22 12:24:59
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
if you  only want to have the text within the tags, you can use this function:

<?php
function showtextintags($text)

{

$text preg_replace("/(\<script)(.*?)(script>)/si""dada""$text");
$text strip_tags($text);
$text str_replace("<!--""&lt;!--"$text);
$text preg_replace("/(\<)(.*?)(--\>)/mi""".nl2br("\\2").""$text);

return 
$text;

}
?>

it will show all the text without tags and (!!!) without javascripts
2004-09-29 08:41:56
http://php5.kiev.ua/manual/ru/function.strip-tags.html
the strip_tags() function in both php 4.3.8 and 5.0.2 (probably many more, but these are the only 2 versions I tested with) have a max tag length of 1024.  If you're trying to process a tag over this limit, strip_tags will not return that line (as if it were an illegal tag).   I noticed this problem while trying to parse a paypal encrypted link button (<input type="hidden" name="encrypted" value="encryptedtext">, with <input> as an allowed tag), which is 2702 characters long.  I can't really think of any workaround for this other than parsing each tag to figure out the length, then only sending it to strip_tags() if its under 1024, but at that point, I might as well be stripping the tags myself.
2004-12-20 20:36:59
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Someone can use attributes like CSS in the tags.
Example, you strip all tagw except <b> then a user can still do <b style="color: red; font-size: 45pt">Hello</b> which might be undesired.

Maybe BB Code would be something.
2005-05-27 15:45:17
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
<?php
/**removes specifed tags from the text where each tag requires a 
     *closing tag and if the later
     *is not found then everything after will be removed
     *typical usage:
     *some html text, array('script','body','html') - all lower case*/
   
public static function removeTags($text,$tags_array){
       
$length strlen($text);
       
$pos =0;
       
$tags_array $array_flip($tags_array);
        while (
$pos $length && ($pos strpos($text,'<',$pos)) !== false){
           
$dlm_pos strpos($text,' ',$pos);
           
$dlm2_pos strpos($text,'>',$pos);
            if (
$dlm_pos $dlm2_pos)$dlm_pos=$dlm2_pos;
           
$which_tag strtolower(substr($text,$pos+1,$dlm_pos-($pos+1)));
           
$tag_length strlen($srch_tag);
            if (!isset(
$tags_array[$which_tag])){
               
//if no tag matches found
               
++$pos;
                continue;
            }
           
//find the end
           
$sec_tag '</'.$which_tag.'>';
           
$sec_pos stripos($text,$sec_tag,$pos+$tag_length);
           
//remove everything after if end of the tag not found
           
if ($sec_pos === false$sec_pos $length-strlen($sec_tag);
           
$rmv_length $sec_pos-$pos+strlen($sec_tag);
           
$text substr_replace($text,'',$pos,$rmv_length);
           
//update length
           
$length $length $rmv_length;
           
$pos++;
        }
        return 
$text;
    }
?>
2005-08-10 15:08:59
http://php5.kiev.ua/manual/ru/function.strip-tags.html
<?php

function remove_tag $tag $data ) {
   
    while ( 
eregi "<" $tag $data ) ) {
       
       
$it    stripos $data "<" $tag   ) ;
               
       
$it2   stripos $data "</" $tag ">" ) + strlen $tag ) + ;
               
       
$temp  substr $data 0    $it  ) ;
   
       
$temp2 substr $data $it2 strlen $data ) ) ;
       
       
$data $temp $temp2 ;
           
    }
   
    return 
$data ;
   
}

?>

this code will remove only and all of the specified tag from a given haystack.
2006-02-01 21:28:49
http://php5.kiev.ua/manual/ru/function.strip-tags.html
<?php
       
/**
    * Works like PHP function strip_tags, but it only removes selected tags.
    * Example:
    *     strip_selected_tags('<b>Person:</b> <strong>Salavert</strong>', 'strong') => <b>Person:</b> Salavert
    */

   
function strip_selected_tags($text$tags = array())
    {
       
$args func_get_args();
       
$text array_shift($args);
       
$tags func_num_args() > array_diff($args,array($text))  : (array)$tags;
        foreach (
$tags as $tag){
            if(
preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU'$text$found)){
               
$text str_replace($found[0],$found[1],$text);
          }
        }

        return 
$text;
    }

?>

Hope you find it useful,

Jose Salavert
2006-02-13 04:21:13
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Here is a recursive function for strip_tags like the one showed in the stripslashes manual page.

<?php
function strip_tags_deep($value)
{
  return 
is_array($value) ?
   
array_map('strip_tags_deep'$value) :
   
strip_tags($value);
}

// Example
$array = array('<b>Foo</b>''<i>Bar</i>', array('<b>Foo</b>''<i>Bar</i>'));
$array strip_tags_deep($array);

// Output
print_r($array);
?>
2006-03-07 13:44:53
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
A simple little function for blocking tags by replacing the '<' and '>' characters with their HTML entities.  Good for simple posting systems that you don't want to have a chance of stripping non-HTML tags, or just want everything to show literally without any security issues:

<?php

function block_tags($string){
   
$replaced_string str_ireplace('<','&lt',$string);
   
$replaced_string str_ireplace('>','&gt',$replaced_string);
    return 
$replaced_string;
}

echo 
block_tags('<b>HEY</b>'); //Returns &ltb&gtHEY&lt/b&gt

?>
2006-04-07 16:57:18
http://php5.kiev.ua/manual/ru/function.strip-tags.html
<?php
function html2txt($document){
$search = array('@<script[^>]*?>.*?</script>@si'// Strip out javascript
               
'@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
               
'@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
               
'@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments including CDATA
);
$text preg_replace($search''$document);
return 
$text;
}
?>

This function turns HTML into text... strips tags, comments spanning multiple lines including CDATA, and anything else that gets in it's way.

It's a frankenstein function I made from bits picked up on my travels through the web, thanks to the many who have unwittingly contributed!
2006-08-09 13:01:54
http://php5.kiev.ua/manual/ru/function.strip-tags.html
To sanitize any user input, you should also consider PEAR's HTML_Safe package.

http://pear.php.net/package/HTML_Safe
2006-09-19 02:57:35
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
<?php

   
/**
     * strip_selected_tags ( string str [, string strip_tags[, strip_content flag]] )
     * ---------------------------------------------------------------------
     * Like strip_tags() but inverse; the strip_tags tags will be stripped, not kept.
     * strip_tags: string with tags to strip, ex: "<a><p><quote>" etc.
     * strip_content flag: TRUE will also strip everything between open and closed tag
     */
   
public function strip_selected_tags($str$tags ""$stripContent false)
    {
       
preg_match_all("/<([^>]+)>/i",$tags,$allTags,PREG_PATTERN_ORDER);
        foreach (
$allTags[1] as $tag){
            if (
$stripContent) {
               
$str preg_replace("/<".$tag."[^>]*>.*<\/".$tag.">/iU","",$str);
            }
           
$str preg_replace("/<\/?".$tag."[^>]*>/iU","",$str);
        }
        return 
$str;
    }

?>
2006-11-05 13:29:51
http://php5.kiev.ua/manual/ru/function.strip-tags.html
This will strip all PHP and HTML out of a file.  Leaves only plain txt.

<?php
// Open the search file
$file fopen($filename'r');
               
// Get rid of all PHP code.       
$search = array('/<\?((?!\?>).)*\?>/s');
       
$text fread($filefilesize($filename));

$new strip_tags(preg_replace($search''$text));

echo 
$new;

fclose($file);
?>

- Strick
2008-01-15 11:52:35
http://php5.kiev.ua/manual/ru/function.strip-tags.html
This adds alot of missing javascript events on the strip_tags_attributes() function from below entries.

Props to MSDN for lots of them ;)

<?php
function strip_tags_attributes($sSource$aAllowedTags = array(), $aDisabledAttributes = array('onabort''onactivate''onafterprint''onafterupdate''onbeforeactivate''onbeforecopy''onbeforecut''onbeforedeactivate''onbeforeeditfocus''onbeforepaste''onbeforeprint''onbeforeunload''onbeforeupdate''onblur''onbounce''oncellchange''onchange''onclick''oncontextmenu''oncontrolselect''oncopy''oncut''ondataavaible''ondatasetchanged''ondatasetcomplete''ondblclick''ondeactivate''ondrag''ondragdrop''ondragend''ondragenter''ondragleave''ondragover''ondragstart''ondrop''onerror''onerrorupdate''onfilterupdate''onfinish''onfocus''onfocusin''onfocusout''onhelp''onkeydown''onkeypress''onkeyup''onlayoutcomplete''onload''onlosecapture''onmousedown''onmouseenter''onmouseleave''onmousemove''onmoveout''onmouseover''onmouseup''onmousewheel''onmove''onmoveend''onmovestart''onpaste''onpropertychange''onreadystatechange''onreset''onresize''onresizeend''onresizestart''onrowexit''onrowsdelete''onrowsinserted''onscroll''onselect''onselectionchange''onselectstart''onstart''onstop''onsubmit''onunload'))
    {
        if (empty(
$aDisabledAttributes)) return strip_tags($sSourceimplode(''$aAllowedTags));

        return 
preg_replace('/<(.*?)>/ie'"'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" implode('|'$aDisabledAttributes) . ")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'"strip_tags($sSourceimplode(''$aAllowedTags)));
    }
?>
2008-03-30 17:05:58
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Here is a suggestion for getting rid of attributes: After you run your HTML through strip_tags(), use the DOM interface to parse the HTML. Recursively walk through the DOM tree and remove any unwanted attributes. Serialize the DOM back to the HTML string.

Don't make the default permit mistake: Make a list of the attributes you want to ALLOW and remove any others, rather than removing a specific list, which may be missing something important.
2008-08-23 20:58:56
http://php5.kiev.ua/manual/ru/function.strip-tags.html
I was looking for a simple way to ban html from review posts, and the like. I have seen a few classes to do it. This line, while it doesn't strip the post, effectively blocks people from posting html in review and other forms.

<?php
if (strlen(strip_tags($review)) < strlen($review)) {
    return 
false;
}
?>

If you want to further get by the tricksters that use & for html links, include this:

<?php
if (strlen(strip_tags($review)) < strlen($review)) {
        return 
false;
} elseif ( 
strpos($review"&") !== false) {
        return 
5;
}
?>

I hope this helps someone out!
2008-09-25 12:15:42
http://php5.kiev.ua/manual/ru/function.strip-tags.html
It's come to my attention that PHP's strip_tags has been doing something funky to some video embed codes that our members submit. I'm not sure the exact situation, but whenever there is a <param> tag that is very long, strip_tags() will completely remove the tag even though it's specified as an allowable tag.

Here's an example of the existing problem:
<?php
// a single very long <param> tag
$html =<<<EOF
<param name="flashVars" value="skin=http%3A//cdn-i.dmdentertainm
...[snip]...
vie%20of%20All-Time"/>
EOF;

echo 
strip_tags($html'<param>');
// this outputs an empty string
?>

This is the function I built to fix and extend the functionality of strip_tags(). The args are:
- $i_html - the HTML string to be parsed
- $i_allowedtags - an array of allowed tag names
- $i_trimtext - whether or not to strip all text outside of the allowed tags

<?php

function real_strip_tags($i_html$i_allowedtags = array(), $i_trimtext FALSE) {
  if (!
is_array($i_allowedtags))
   
$i_allowedtags = !empty($i_allowedtags) ? array($i_allowedtags) : array();
 
$tags implode('|'$i_allowedtags);

  if (empty(
$tags))
   
$tags '[a-z]+';

 
preg_match_all('@</?\s*(' $tags ')(\s+[a-z_]+=(\'[^\']+\'|"[^"]+"))*\s*/?>@i'$i_html$matches);

 
$full_tags $matches[0];
 
$tag_names $matches[1];

  foreach (
$full_tags as $i => $full_tag) {
    if (!
in_array($tag_names[$i], $i_allowedtags))
      if (
$i_trimtext)
        unset(
$full_tags[$i]);
      else
       
$i_html str_replace($full_tag''$i_html);
  }

  return 
$i_trimtext implode(''$full_tags) : $i_html;
}
?>

And here's an example with the a block of full video embed code with <object><embed><param> and some extraneous HTML:

<?php
$html 
=<<<EOF
<em><div><object type="application/x-shock
...[snip]...
me.html">Wal-Mart Makes The Worst Movie of All-Time</a> -- powered by whatever</div></em>
EOF;

$good_html real_strip_tags($html, array('object''embed''param'), TRUE);

?>

Now $good_html contains only the specified tags and none of the "powered by" type text. I hope someone finds this as useful as I needed it to be. :)
2008-10-20 13:21:48
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Hi. I made a function that removes the HTML tags along with their contents:

Function:
<?php
function strip_tags_content($text$tags ''$invert FALSE) {

 
preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si'trim($tags), $tags);
 
$tags array_unique($tags[1]);
   
  if(
is_array($tags) AND count($tags) > 0) {
    if(
$invert == FALSE) {
      return 
preg_replace('@<(?!(?:'implode('|'$tags) .')\b)(\w+)\b.*?>.*?</\1>@si'''$text);
    }
    else {
      return 
preg_replace('@<('implode('|'$tags) .')\b.*?>.*?</\1>@si'''$text);
    }
  }
  elseif(
$invert == FALSE) {
    return 
preg_replace('@<(\w+)\b.*?>.*?</\1>@si'''$text);
  }
  return 
$text;
}
?>

Sample text:
$text = '<b>sample</b> text with <div>tags</div>';

Result for strip_tags($text):
sample text with tags

Result for strip_tags_content($text):
 text with 

Result for strip_tags_content($text, '<b>'):
<b>sample</b> text with 

Result for strip_tags_content($text, '<b>', TRUE);
 text with <div>tags</div>

I hope that someone is useful :)
2008-11-12 10:05:25
http://php5.kiev.ua/manual/ru/function.strip-tags.html
I think it is worth mentioning that if some tags are allowed using the second parameter, this function does not allow to strip attributes within the allowed tags and hence should not be used against XSS vulnerabilities.

One can still execute javascript by 2 means:
- by inserting attributes that typically accept javascript 
  >> onClick="alert('XSS');"
- by using styles 
  >> style="width:expression(alert('XSS'));" (works on IE7 and probably other versions)
2009-01-13 21:03:24
http://php5.kiev.ua/manual/ru/function.strip-tags.html
strip_tags will strip '<' and the string behind, like this

<?php
$str 
= <<<EOF
123 < 456
<a>link</a>
bbb
EOF;

echo 
strip_tags($str);
?>

will output:
123

---------------------------------
this function will repiar this

<?php
function will_strip_tags($str) {
    do {
       
$count 0;
       
$str preg_replace('/(<)([^>]*?<)/' '&lt;$2' $str , -$count);
    } while (
$count 0);
   
$str strip_tags($str);
   
$str str_replace('>' '&gt;' $str);
    return 
$str;
}

echo 
will_strip_tags($str);
?>

will output:
123 &lt; 456
link
bbb
2009-01-17 04:01:10
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Maybe also a usefull function for someone.

<?php
function removeUnsafeAttributesAndGivenTags($input$validTags '')
{
   
$regex '#\s*<(/?\w+)\s+(?:on\w+\s*=\s*(["\'\s])?.+?
\(\1?.+?\1?\);?\1?|style=["\'].+?["\'])\s*>#is'
;
    return 
preg_replace($regex'<${1}>',strip_tags($input$validTags));
}
?>
2009-01-26 16:51:30
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Note the different outputs from different versions of the same tag:

<?php // striptags.php
$data '<br>Each<br/>New<br />Line';
$new  strip_tags($data'<br>');
var_dump($new);  // OUTPUTS string(21) "<br>EachNew<br />Line"

<?php // striptags.php
$data '<br>Each<br/>New<br />Line';
$new  strip_tags($data'<br/>');
var_dump($new); // OUTPUTS string(16) "Each<br/>NewLine"

<?php // striptags.php
$data '<br>Each<br/>New<br />Line';
$new  strip_tags($data'<br />');
var_dump($new); // OUTPUTS string(11) "EachNewLine"
?>
2009-02-17 13:10:27
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Strip tags doesn't work fine if we have '<' symbol in the string followed immediately by any letter. but it doed work fine if there is a space after '<' symbol. e.g.

<?php
strip_tags
('<p>1<4</p>');  //won't work fine
strip_tags('<p>1 < 4</p>');  //will work fine
?>

to solve this problem, I used a simple logic. This code will replace '<' by html char, if it not a part of html tag.

My version of strip_tags is as follow:

<?php
function my_strip_tags($str) {
   
$strs=explode('<',$str);
   
$res=$strs[0];
    for(
$i=1;$i<count($strs);$i++)
    {
        if(!
strpos($strs[$i],'>'))
           
$res $res.'&lt;'.$strs[$i];
        else
           
$res $res.'<'.$strs[$i];
    }
    return 
strip_tags($res);   
}
?>
2009-03-03 05:22:30
http://php5.kiev.ua/manual/ru/function.strip-tags.html
a function that decides if < is a start of a tag or a lower than / lower than + equal:

<?php
function lt_replace($str){
    return 
preg_replace("/<([^[:alpha:]])/"'&lt;\\1'$str);
}
?>

It's to be used before strip_slashes.
2009-03-06 10:45:05
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Improperly formatted javascript being add to tags and the limit of 15 instences of recursion before memory allocation runs out are some of the concerns involved in coding.  Here is the code that I created to leave tags intact but strip scripting from only inside the tags...

<?php
function strip_javascript($filter){
   
   
// realign javascript href to onclick
   
$filter preg_replace("/href=(['\"]).*?javascript:(.*)?
\\1/i"
"onclick=' $2 '"$filter);

   
//remove javascript from tags
   
while( preg_match("/<(.*)?javascript.*?\(.*?((?>[^()]+)
|(?R)).*?\)?\)(.*)?>/i"
$filter))
       
$filter preg_replace("/<(.*)?javascript.*?\(.*?((?>
[^()]+)|(?R)).*?\)?\)(.*)?>/i"
"<$1$3$4$5>"$filter);
             
   
// dump expressions from contibuted content
   
if(0$filter preg_replace("/:expression\(.*?((?>[^
(.*?)]+)|(?R)).*?\)\)/i"
""$filter);

    while( 
preg_match("/<(.*)?:expr.*?\(.*?((?>[^()]+)|(?
R)).*?\)?\)(.*)?>/i"
$filter))
       
$filter preg_replace("/<(.*)?:expr.*?\(.*?((?>[^()]
+)|(?R)).*?\)?\)(.*)?>/i"
"<$1$3$4$5>"$filter);
       
   
// remove all on* events   
   
while( preg_match("/<(.*)?\s?on.+?=?\s?.+?(['\"]).*?\\2
\s?(.*)?>/i"
$filter) )
       
$filter preg_replace("/<(.*)?\s?on.+?=?\s?.+?
(['\"]).*?\\2\s?(.*)?>/i"
"<$1$3>"$filter);

    return 
$filter;
}
?>

As you can see this does not clean up correctly... it does 
however remove dangerous stuff... 

<a href=javascript: { {({}{}()())}alert('xss') ) ) }>

<div onload..;,;..'alert(\"xss_attack\");'>

<a href='javascript:{ alert(\"xss_attack\"); otherxss();}'
 onclick= 'alert(\"xss_attack\");' onhover='alert
(\"xss_attack\");' onmouseout=alert(\"xss_attack\") 
class='thisclass'> link</a>

style='width:expression(alert(\"xss_attack\"));'

This can be completed before using strip_tags().
2009-03-08 12:55:37
http://php5.kiev.ua/manual/ru/function.strip-tags.html
An easy way to clean a string of all CDATA encapsulation.

<?php
function strip_cdata($string)
{
   
preg_match_all('/<!\[cdata\[(.*?)\]\]>/is'$string$matches);
    return 
str_replace($matches[0], $matches[1], $string);
}
?>

Example: echo strip_cdata('<![CDATA[Text]]>');
Returns: Text
2009-03-26 14:52:17
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Works on shortened <?...?> syntax and thus also will remove XML processing instructions.
2009-04-05 11:10:58
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Here's a function that verify if in a string have broken HTML tags, returning true if do. Useful for previning broken tags to affect the page.

<?php
# Example usage: broken_tags("<b>This is a string</u>") returns TRUE, broken_tags("<b>This is a string</b>") returns FALSE.
function broken_tags($str)
{
   
preg_match_all("/(<\w+)(?:.){0,}?>/"$str$v1);
   
preg_match_all("/<\/\w+>/"$str$v2);
   
$open array_map('strtolower'$v1[1]);
   
$closed array_map('strtolower'$v2[0]);
    foreach (
$open as $tag)
    {
       
$end_tag preg_replace("/<(.*)/""</$1>"$tag);
        if (!
in_array($end_tag$closed)) return true;
        unset(
$closed[array_search($end_tag$closed)]);
    }
    return 
false;
}
?>
2009-06-07 03:41:00
http://php5.kiev.ua/manual/ru/function.strip-tags.html
To check for broken tags an easier approach would be to use xml_parse(). You can also get a descriptive error with xml_get_error_code().
2009-06-09 06:41:19
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Here is a function like strip_tags, only it removes only the tags (with attributes) specified:

<?php
function strip_only($str$tags) {
    if(!
is_array($tags)) {
       
$tags = (strpos($str'>') !== false explode('>'str_replace('<'''$tags)) : array($tags));
        if(
end($tags) == ''array_pop($tags);
    }
    foreach(
$tags as $tag$str preg_replace('#</?'.$tag.'[^>]*>#is'''$str);
    return 
$str;
}

$str '<p style="text-align:center">Paragraph</p><strong>Bold</strong><br/><span style="color:red">Red</span><h1>Header</h1>';

echo 
strip_only($str, array('p''h1'));
echo 
strip_only($str'<p><h1>');
?>

Both return:
Paragraph<strong>Bold</strong><br/><span style="color:red">Red</span>Header

Hope this helps somebody else
2009-09-16 13:03:02
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Here is support for stripping content for the reverse strip_tags function:

<?php
function strip_only($str$tags$stripContent false) {
   
$content '';
    if(!
is_array($tags)) {
       
$tags = (strpos($str'>') !== false explode('>'str_replace('<'''$tags)) : array($tags));
        if(
end($tags) == ''array_pop($tags);
    }
    foreach(
$tags as $tag) {
        if (
$stripContent)
             
$content '(.+</'.$tag.'[^>]*>|)';
         
$str preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is'''$str);
    }
    return 
$str;
}

$str '<font color="red">red</font> text';
$tags 'font';
$a strip_only($str$tags); // red text
$b strip_only($str$tagstrue); // text
?>

Note this function always assumed no two tags start the same way (e.g. <bla> and <blas>) and therefore censors blas along with bla.
2010-03-01 09:07:40
http://php5.kiev.ua/manual/ru/function.strip-tags.html
This could be overkill but this strips all HTML tags and gives you the option to preserve the ones you define. It also takes into account tags like <script> removing all the javascript, too! You can also strip out all the content between any tag that has an opening and closing tag, like <table>, <object>, etc.

<?php 
   
function remove_HTML($s $keep '' $expand 'script|style|noframes|select|option'){
       
/**///prep the string
       
$s ' ' $s;
       
       
/**///initialize keep tag logic
       
if(strlen($keep) > 0){
           
$k explode('|',$keep);
            for(
$i=0;$i<count($k);$i++){
               
$s str_replace('<' $k[$i],'[{(' $k[$i],$s);
               
$s str_replace('</' $k[$i],'[{(/' $k[$i],$s);
            }
        }
       
       
//begin removal
        /**///remove comment blocks
       
while(stripos($s,'<!--') > 0){
           
$pos[1] = stripos($s,'<!--');
           
$pos[2] = stripos($s,'-->'$pos[1]);
           
$len[1] = $pos[2] - $pos[1] + 3;
           
$x substr($s,$pos[1],$len[1]);
           
$s str_replace($x,'',$s);
        }
       
       
/**///remove tags with content between them
       
if(strlen($expand) > 0){
           
$e explode('|',$expand);
            for(
$i=0;$i<count($e);$i++){
                while(
stripos($s,'<' $e[$i]) > 0){
                   
$len[1] = strlen('<' $e[$i]);
                   
$pos[1] = stripos($s,'<' $e[$i]);
                   
$pos[2] = stripos($s,$e[$i] . '>'$pos[1] + $len[1]);
                   
$len[2] = $pos[2] - $pos[1] + $len[1];
                   
$x substr($s,$pos[1],$len[2]);
                   
$s str_replace($x,'',$s);
                }
            }
        }
       
       
/**///remove remaining tags
       
while(stripos($s,'<') > 0){
           
$pos[1] = stripos($s,'<');
           
$pos[2] = stripos($s,'>'$pos[1]);
           
$len[1] = $pos[2] - $pos[1] + 1;
           
$x substr($s,$pos[1],$len[1]);
           
$s str_replace($x,'',$s);
        }
       
       
/**///finalize keep tag
       
for($i=0;$i<count($k);$i++){
           
$s str_replace('[{(' $k[$i],'<' $k[$i],$s);
           
$s str_replace('[{(/' $k[$i],'</' $k[$i],$s);
        }
       
        return 
trim($s);
    }
?>
2010-04-16 19:58:50
http://php5.kiev.ua/manual/ru/function.strip-tags.html
I thought someone else might find this useful... a simple way to strip BBCode:

<?php

$bbcode_str 
"Here is some [b]bold text[/b] and some [color=#FF0000]red text[/color]!";

$plain_text strip_tags(str_replace(array('[',']'), array('<','>'), $bbcode_str));

//Outputs: Here is some bold text, and some red text!

?>
2010-07-08 06:40:49
http://php5.kiev.ua/manual/ru/function.strip-tags.html
With most web based user input of more than a line of text, it seems I get 90% 'paste from Word'. I've developed this fn over time to try to strip all of this cruft out. A few things I do here are application specific, but if it helps you - great, if you can improve on it or have a better way - please - post it... 

<?php

   
function strip_word_html($text$allowed_tags '<b><i><sup><sub><em><strong><u><br>')
    {
       
mb_regex_encoding('UTF-8');
       
//replace MS special characters first
       
$search = array('/&lsquo;/u''/&rsquo;/u''/&ldquo;/u''/&rdquo;/u''/&mdash;/u');
       
$replace = array('\'''\'''"''"''-');
       
$text preg_replace($search$replace$text);
       
//make sure _all_ html entities are converted to the plain ascii equivalents - it appears
        //in some MS headers, some html entities are encoded and some aren't
       
$text html_entity_decode($textENT_QUOTES'UTF-8');
       
//try to strip out any C style comments first, since these, embedded in html comments, seem to
        //prevent strip_tags from removing html comments (MS Word introduced combination)
       
if(mb_stripos($text'/*') !== FALSE){
           
$text mb_eregi_replace('#/\*.*?\*/#s'''$text'm');
        }
       
//introduce a space into any arithmetic expressions that could be caught by strip_tags so that they won't be
        //'<1' becomes '< 1'(note: somewhat application specific)
       
$text preg_replace(array('/<([0-9]+)/'), array('< $1'), $text);
       
$text strip_tags($text$allowed_tags);
       
//eliminate extraneous whitespace from start and end of line, or anywhere there are two or more spaces, convert it to one
       
$text preg_replace(array('/^\s\s+/''/\s\s+$/''/\s\s+/u'), array(''''' '), $text);
       
//strip out inline css and simplify style tags
       
$search = array('#<(strong|b)[^>]*>(.*?)</(strong|b)>#isu''#<(em|i)[^>]*>(.*?)</(em|i)>#isu''#<u[^>]*>(.*?)</u>#isu');
       
$replace = array('<b>$2</b>''<i>$2</i>''<u>$1</u>');
       
$text preg_replace($search$replace$text);
       
//on some of the ?newer MS Word exports, where you get conditionals of the form 'if gte mso 9', etc., it appears
        //that whatever is in one of the html comments prevents strip_tags from eradicating the html comment that contains
        //some MS Style Definitions - this last bit gets rid of any leftover comments */
       
$num_matches preg_match_all("/\<!--/u"$text$matches);
        if(
$num_matches){
             
$text preg_replace('/\<!--(.)*--\>/isu'''$text);
        }
        return 
$text;
    }
?>
2010-08-27 22:04:16
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Note that strip_tags may stumble when it encounters two consecutive quotes. Regardless of whether that's a bug or a feature (different PHP versions seem to behave differently) here's a workaround:

<?php
  $wtf 
'
    <p>First line</p>
    <a href=\"foo">bar</a>
    <p>Second line</p>
    <a href=\"foo\"">bar</a>
    <p>Third line</p>
  '
;
  echo 
'Raw: ' $wtf "\n";
  echo 
'strip_tags(): ' strip_tags ($wtf);
  echo 
'Regexp: ' preg_replace ('/<[^>]*>/'''$wtf);
?>

Raw output:

  <p>First line</p>
  <a href=\"foo">bar</a>
  <p>Second line</p>
  <a href=\"foo\"">bar</a>
  <p>Third line</p>

strip_tags() output:

  First line
  bar
  Third line

preg_replace() output:

  First line
  bar
  Second line
  bar
  Third line
2010-11-19 04:30:30
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
IMO, the function should allow you to remove any tag that you specify.  The structure could be something like this:

strip_tags($string,$allow_or_remove_listed,$list)

As an example:

<?php
$str 
"<p><strong>This is a string.</strong> <a href="http://www.example.com/">Some Random Website</a>";
$str strip_tags($str,"remove","<strong>");
echo 
$str;
?>

would remove the <strong> tag.
2011-01-31 12:46:55
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
As noted in the documentation strip_tags would strip php and comments tags even if they are add to $allowable_tags.

Here is a little workaround for this issue:
<?php
function stripTags($text$tags)
{
 
 
// replace php and comments tags so they do not get stripped 
 
$text preg_replace("@<\?@""#?#"$text);
 
$text preg_replace("@<!--@""#!--#"$text);
 
 
// strip tags normally
 
$text strip_tags($text$tags);
 
 
// return php and comments tags to their origial form
 
$text preg_replace("@#\?#@""<?"$text);
 
$text preg_replace("@#!--#@""<!--"$text);
 
  return 
$text;
}
?>

The function would replace the tags to hashes so strip_tags would not identify them as normal tags, and then when strip_tags does its job the tags are modified back to their original form.
2011-02-03 01:44:27
http://php5.kiev.ua/manual/ru/function.strip-tags.html
strip_tags destroys the whole HTML behind the tags with invalid attributes. Like <img src="/images/image.jpg""> (look, there is an odd quote before >.)

So I wrote function which fixes unsafe attributes and replaces odd " and ' quotes with &quot; and &#39;.

<?php
function fix_unsafe_attributes($s) {
 
$out false;
  while (
preg_match('/<([A-Za-z])[^>]*?>/'$s$iPREG_OFFSET_CAPTURE)) { // find where the tag begins
   
$i $i[1][1]+1;
   
$out.= substr($s0$i);
   
$s substr($s$i);

   
// scan attributes and find odd " and '
   
while (((($i1 strpos($s'"')) || 1) && (($i2 strpos($s'\'')) || 1)) && ($i1 !== false || $i2 !== false) &&
           ((
$i = (int)(($i1 !== false) && ($i2 !== false) ? ($i1 $i2 $i1 $i2) : ($i1 == false $i2 $i1))) !== false) &&
           (((
$c strpos($s'>')) === false) || ($i $c))) {

     
$c $s{$i};
      if ((
$i 1) || ($s{$i-1} != '=')) {
       
$out.= substr($s0$i).($s{$i} == '"' '&quot;' '&#39;'); // replace odd " and '
       
$s substr($s$i+1);
      }else {
       
$i++;
       
$out.= substr($s0$i);
       
$s substr($s$i);

        if ((
$i strpos($s$c)) !== false) {
         
$i++;
         
$out.= substr($s0$i);
         
$s substr($s$i);
        }
      }
    }
  }
  return 
$out.$s;
}
?>

Maybe this function can be rewritten with simple regular expression but I have no luck to make it quickly.
2011-02-24 15:06:32
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
If you want to strip ANSI escape color codes.
<?php
function strip_ansi($string) {
  return 
preg_replace('/\e\[[;?0-9]*[0-9A-Za-z]/'''$string);
}
?>
2011-06-16 16:12:20
http://php5.kiev.ua/manual/ru/function.strip-tags.html
this is just for strip the inside tags 

<?php
$allow 
'<p><ul><li><b><strong>';

$str '<p style="text-align:center">Paragraph</p><strong>Bold</strong><br/><span style="color:red">Red</span><h1>Header</h1>';

$result strip_tags($str,$allow);
$result clean_inside_tags($result,$allow);

echo 
'<textarea>'.$result.'</textarea>';

//Clean the inside of the tags
function clean_inside_tags($txt,$tags){
   
   
preg_match_all("/<([^>]+)>/i",$tags,$allTags,PREG_PATTERN_ORDER);

    foreach (
$allTags[1] as $tag){
       
$txt preg_replace("/<".$tag."[^>]*>/i","<".$tag.">",$txt);
    }

    return 
$txt;
}

?>
2011-10-10 07:09:14
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
The following is an easy way to use strip_tags() with a simple array or a multidimensional array.

<?php

function strip_tags_array($data$tags null)
{
   
$stripped_data = array();
    foreach (
$data as $value)
    {
        if (
is_array($value))
        {
           
$stripped_data[] = strip_tags_array($value$tags);
        }
        else
        {
           
$stripped_data[] = strip_tags($value$tags);
        }
    }
    return 
$stripped_data;
}

?>
2011-10-20 12:40:44
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Here is the function created for strip tags with sub string

<?php 
function displaySubStringWithStrip($string$length=NULL)
{
    if (
$length == NULL)
           
$length 50;
   
   
$stringDisplay substr(strip_tags($string), 0$length);
    if (
strlen(strip_tags($string)) > $length)
       
$stringDisplay .= ' ...';
    return 
$stringDisplay;
}

?>
2011-11-14 01:01:36
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Автор:
Function to simply test if a given location index is inside a tag in the string

<?php
function in_tag($str,$index) {
   
//test if $index occurs inside an html tag in $str

   
$before substr($str,0,$index);
   
$after substr($str,$index);

   
$prev_lt strrpos($before,'<');
   
$next_lt strpos($after,'<') + $index;

   
$prev_gt strrpos($before,'>');
   
$next_gt strpos($after,'>') + $index;

    return (
$prev_gt $prev_lt) && ($next_lt $next_gt);
}
?>
2012-01-05 09:31:56
http://php5.kiev.ua/manual/ru/function.strip-tags.html
Here is a far better function for the atypical process of stripping tags:

<?php
function strip_html_tags$text )
{
   
$text preg_replace(
        array(
         
// Remove invisible content
           
'@<head[^>]*?>.*?</head>@siu',
           
'@<style[^>]*?>.*?</style>@siu',
           
'@<script[^>]*?.*?</script>@siu',
           
'@<object[^>]*?.*?</object>@siu',
           
'@<embed[^>]*?.*?</embed>@siu',
           
'@<applet[^>]*?.*?</applet>@siu',
           
'@<noframes[^>]*?.*?</noframes>@siu',
           
'@<noscript[^>]*?.*?</noscript>@siu',
           
'@<noembed[^>]*?.*?</noembed>@siu',
         
// Add line breaks before and after blocks
           
'@</?((address)|(blockquote)|(center)|(del))@iu',
           
'@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
           
'@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
           
'@</?((table)|(th)|(td)|(caption))@iu',
           
'@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
           
'@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
           
'@</?((frameset)|(frame)|(iframe))@iu',
        ),
        array(
           
' '' '' '' '' '' '' '' '' ',"$0""$0""$0""$0""$0""$0","$0""$0",), $text );
     
    return 
strip_html_tags$text '<b><a>' );
}
?>
2012-02-06 15:15:28
http://php5.kiev.ua/manual/ru/function.strip-tags.html
or you can use the sledgehammer approach to get rid of everything betwean any tags:

preg_replace ( "'<[^>]+>'U", "", $textstring);
2012-03-29 14:09:06
http://php5.kiev.ua/manual/ru/function.strip-tags.html

    Поддержать сайт на родительском проекте КГБ