PHP : Strip specific tags from HTML string with source code

We can able to strip HTML tags from string in PHP by calling the function preg_replace(). It will compare tags by regular expression and strip from formatted string HTML. Below is the function it will strip given tag from string HTML. This function accepts tag name as argument.

Source Code:

/**
 * Custom Function for Remove Specific Tag in the string.
 */
function strip_single_html_tags($tag,$string) {
  $string =  ('/<'.$tag.'[^>]*>/i', '', $string);
  $string = preg_replace('/<\/'.$tag.'>/i', '', $string);
  return $string;
}

 

Function call
$tag = 'div';
$string = '
<body>
  <h2>CodeExpertz</h2>
  <div class="test-div">This div will strip</div>
  <p> Test content </p>
</body>
';
$stripString = strip_single_html_tags($tag,$string);
print $stripString;
 
//Output
<body>
  <h2>CodeExpertz</h2>
  This div will strip
  <p> Test content </p>
</body>
Category: