php remove the links and content
Hi all I've a little php question:
I've a many strings like t开发者_StackOverflowhat:
$content = "Hi I am a <a href='http://blabla' ...>black</a> cat";
How can i convert this string to:
$content = "Hi I am a cat";
I tried that but doesn't works...
$content = preg_replace("/<a href=.*?>(.*?)<\/a>/","$1",$content);
It looks just about right.
I just tried this and it seemed to work fine:
$content = preg_replace("/<a href=.*?>(.*?)<\/a>/","",$content);
No use REGEX!!!! Use 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/
If you are simply trying to get rid of the "black" as well, you might want to try 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;
精彩评论