Home  >  Article  >  Backend Development  >  PHP strip_tags method to retain multiple HTML tags

PHP strip_tags method to retain multiple HTML tags

高洛峰
高洛峰Original
2017-01-03 09:45:261268browse

This article introduces the method of PHP strip_tags function to retain multiple HTML tags. You can use the second parameter to set tags that do not need to be deleted, mainly involving the second parameter of strip_tags

strip_tags function

Syntax
string strip_tags (string str [, string allowable_tags])
Returns a string with HTML tags removed; you can use the second parameter to set tags that do not need to be deleted.

Usage:

Premise: If there is such a string now,

$str = "

我来自PHP中文网

";

1, without retaining any HTML tags, the code will be like this:

echo strip_tags($str); 
// 输出:我来自PHP中文网

2. If you want to retain only the 3499910bf9dac5ae3c52d5ede7383485 tag, you only need to write the 3499910bf9dac5ae3c52d5ede7383485 string into the second parameter of strip_tags:

echo strip_tags($str, ""); 
// 输出:我来自PHP中文网

3. To retain e388a4556c0f65e1904146cc1a846bee and < ;b>...Multiple tags, just separate the multiple tags with spaces and write them to the second parameter of strip_tags:

echo strip_tags($str, "

"); // 输出:

我来自PHP中文网

What if you want to use php to delete specific tags in the html tag?

This requires code to implement, as follows:

function strip_selected_tags($text, $tags = array()) {
  $args = func_get_args();
  $text = array_shift($args);
  $tags = func_num_args() > 2 ? array_diff($args, array($text)) : (array) $tags;
  foreach($tags as $tag) {
    if (preg_match_all('/<'.$tag.
        '[^>]*>([^<]*)/iu', $text, $found)) {
      $text = str_replace($found[0], $found[1], $text);
    }
  }
 
  return preg_replace('/(<('.join('|', $tags).
    ')( | |.)*/>)/iu', '', $text);
}
 
$str = "[url="] 123[/url]";
    echo strip_selected_tags($str, array('b'));

##Please pay attention to more related articles on how PHP strip_tags retains multiple HTML tags. PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]