如何从PHP中的字符串中删除带有文本的锚标记[重复]

问题描述 投票:2回答:4

这个问题在这里已有答案:

我有bellow字符串,其中包含内容和锚标记:

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

我想删除锚标记及其文本(链接在其中)

我已经尝试过使用strip_tags,但它仍然是字符串中的锚文本,之后,我尝试使用preg_replace这个例子:

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

但得到与strip_tags相同的结果。

在删除锚标签后,我只想要“我有很多文字”。

任何的想法?

php
4个回答
7
投票

一种方法是在.*<a中使用a>通配符

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

如果出现多个锚点,您可以使用.*?。制作你的模式'/ <a.*?a>/'


2
投票

怎么样做爆炸。对于上面的例子

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

2
投票

你可以简单地使用stristr()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);

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用于删除所有标签及其内容请参阅php手册Strip Tags的第一条评论

© www.soinside.com 2019 - 2024. All rights reserved.