how to remove a tag and its contents using regular expression?

前端 未结 5 2491
囚心锁ツ
囚心锁ツ 2021-02-20 06:09

$str = \'some text tag contents more text \';

My questions are: How to retrieve content tag contents which is between

5条回答
  •  青春惊慌失措
    2021-02-20 06:50

    I tested this function, it works for nested tags too, use true/false to exclude/include your tags. Found here: https://www.php.net/manual/en/function.strip-tags.php

    /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.*?>.*?@si', '', $text);
        }
        else {
          return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?@si', '', $text);
        }
      }
      elseif($invert == FALSE) {
        return preg_replace('@<(\w+)\b.*?>.*?@si', '', $text);
      }
      return $text;
    }
    
    
    
    
    // Sample text:
    $text = 'sample text with 
    tags
    '; // Result for: echo strip_tags_content($text); // text with // Result for: echo strip_tags_content($text, ''); // sample text with // Result for: echo strip_tags_content($text, '', TRUE); // text with
    tags

提交回复
热议问题