How to remove anchor tag with its text from the string in PHP

时间:2017-12-18 06:05:21

标签: php

I have bellow string which has content and anchor tag:

$string = 'I am a lot of text with <a href="#">links in it</a>';

and I want to remove anchor tag with its text(links in it)

I have tried with strip_tags but it remains anchor text in the string, after that, I have tried with preg_replace with this example:

$string = preg_replace('/<a[^>]+>([^<]+)<\/a>/i', '\1', $string);

but getting same result as strip_tags.

I just want "I am a lot of text with" after removing anchor tag.

Any idea?

4 个答案:

答案 0 :(得分:7)

One way is to use .* wildcard inside <a and a>

$string = 'I am a lot of text with <a href="#">links in it</a>';
$string = preg_replace('/ <a.*a>/', '', $string);
echo $string;

In case of multiple anchor occurence, you can use .*?. Making your pattern '/ <a.*?a>/'

答案 1 :(得分:2)

How about doing it for explode. For your above example

$string = 'I am a lot of text with <a href="#">links in it</a>';
$string =explode("<a",$string);
echo $string[0];

答案 2 :(得分:2)

you can simply use stristr() for this(DEMO):

<?php
$string = 'I am a lot of text with <a href="#">links in it</a> Lorem Ipsum';
//Get part before the <a
$stringBfr = stristr($string,'<a', true);
//get part after and along with </a>
$stringAftr = stristr($string,'</a>');
//Remove </a>
$stringAftr = str_replace('</a>', '', $stringAftr);
//concatenate the matched string.
$string = $stringBfr.$stringAftr;
var_dump($string);

答案 3 :(得分:0)

 <?php 
    function strip_tags_content($text, $tags = '', $invert = FALSE) { 

      preg_match_all('/<(.+?)[\s]*\/?[\s]*>/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.*?>.*?</\1>@si', '', $text); 
        } 
        else { 
          return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text); 
        } 
      } 
      elseif($invert == FALSE) { 
        return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text); 
      } 
      return $text; 
    } 

echo strip_tags_content('<a href="google.com">google.com</a>')

    ?> 

Strip_tags_content is used to delete all tags along with it's content See the first comment of php manual Strip Tags

相关问题