2

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?

Mr.Happy
  • 2,639
  • 9
  • 40
  • 73
  • If you know exactly from where to where in the string the anchor is located, you could just use `substr()`. Or do you not know that? – Geshode Dec 18 '17 at 06:08
  • 2
    [H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ](https://stackoverflow.com/a/1732454/2394254) – mega6382 Dec 18 '17 at 06:09
  • @Geshode It can be anywhere from the sting. – Mr.Happy Dec 18 '17 at 06:13

4 Answers4

6

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>/'

Goma
  • 2,018
  • 1
  • 10
  • 19
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];
imox
  • 1,544
  • 12
  • 12
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);
mega6382
  • 9,211
  • 17
  • 48
  • 69
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

Saad Suri
  • 1,352
  • 1
  • 14
  • 26