这个问题在这里已有答案:
我有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
相同的结果。
在删除锚标签后,我只想要“我有很多文字”。
任何的想法?
一种方法是在.*
和<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>/'
怎么样做爆炸。对于上面的例子
$string = 'I am a lot of text with <a href="#">links in it</a>';
$string =explode("<a",$string);
echo $string[0];
你可以简单地使用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);
<?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的第一条评论