php删除链接和内容

时间:2011-08-16 20:27:57

标签: php string preg-replace

大家好我有一个小问题:

我有很多这样的字符串:

$content = "Hi I am a <a href='http://blabla' ...>black</a> cat";

如何将此字符串转换为:

$content = "Hi I am a cat";

我尝试了但不起作用......

$content = preg_replace("/<a href=.*?>(.*?)<\/a>/","$1",$content);

2 个答案:

答案 0 :(得分:8)

看起来恰到好处。

我刚尝试了这个,似乎工作正常:

$content = preg_replace("/<a href=.*?>(.*?)<\/a>/","",$content);

答案 1 :(得分:1)

No use REGEX!!!!使用strip_tags

echo strip_tags( "Hi I am a <a href='http://blabla' ...> black</a> cat" );
// Hi I am a  black cat 
// (there will be a double space there because a space comes before and after
// the opening for the <a> tag. You can use str_replace('  ', ' ', $val) to get
// rid of all double spaces/

如果你只是想摆脱“黑色”,你可能想尝试DomDocument:

$doc = new DomDocument();
$doc->loadXML( "<root>" . // you'll need a root.
       "Hi I am a <a href='http://blabla' ...> black</a> cat".
"</root>");
$nodes = array();
foreach( $doc->getElementsByTagName('a') as $item )
{
   $nodes[]=$item;
}
foreach( $nodes as $node )
{
   if( $node->parentNode ) $node->parentNode->removeChild($node);
}
echo $doc->documentElement->nodeValue;