Home >Backend Development >PHP Tutorial >About PHP strip_tags retaining multiple HTML tags

About PHP strip_tags retaining multiple HTML tags

不言
不言Original
2018-06-14 09:28:192303browse

This article mainly introduces the method of PHP strip_tags to retain multiple HTML tags. Friends who need it can refer to it.

This article introduces the method of PHP strip_tags function to retain multiple HTML tags. You can use the second one. Parameters 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 = "<p>我来自<b><a href=&#39;//www.php.cn&#39;>php中文网</a></b></p>";

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, "<a>"); 
// 输出:我来自<a href=&#39;//www.php.cn&#39;>php中文网</a>

3. To retain the a3416afe407520e676020c5a029970b8... multiple tags, just separate the multiple tags with spaces and write them to the second parameter of strip_tags:

echo strip_tags($str, "<p> <b>"); 
// 输出:<p>我来自<b>php中文网</b></p>

If you want to use php to delete html What about specific tags in markup?

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(&#39;/<&#39;.$tag.
        &#39;[^>]*>([^<]*)</&#39;.$tag.
        &#39;>/iu&#39;, $text, $found)) {
      $text = str_replace($found[0], $found[1], $text);
    }
  }

  return preg_replace(&#39;/(<(&#39;.join(&#39;|&#39;, $tags).
    &#39;)( | |.)*/>)/iu&#39;, &#39;&#39;, $text);
}

$str = "[url="] 123[/url]";
    echo strip_selected_tags($str, array(&#39;b&#39;));

The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to PHP Chinese net!

Related recommendations:

Use html_entity_decode to implement HTML entity escaping in php

##

The above is the detailed content of About PHP strip_tags retaining multiple HTML tags. For more information, please follow other related articles on the 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 admin@php.cn