Loading Image

Almost there...

Loading Image

Loading...

Remove tags and the content between them

This PHP functions uses dynamic opening and closing tags and searches for them in the supplied string. It then removes them with its content.
7 February 2017 - 10:00
Downloads: 470
Category: PHP
Remove tags and its content
Overview

In PHP you get the strip_tags() function which allows you to remove all or only specific tags from your string, but it doesn't remove the content between the tags. This is where this function comes in handy. It uses dynamic opening and closing tags and searches for them in the supplied string, and them removes the tags and the content between them.

PHP Code:
<?php
$string = 'Some valid and <script>some invalid</script> text <script>which needs to be removed</script>!';

$out = delete_all_between('<script>', '</script>', $string);

print($out);

function delete_all_between($beginning, $end, $string) {

  while ( ( $pos = strpos( $string, $beginning, $pos ) ) !== false ) {

      $beginningPos = strpos($string, $beginning);
      $endPos = strpos($string, $end);

      $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

      $string = str_replace($textToDelete, '', $string);

      $pos++;
  }

  return $string;
}
?>