2011-08-16 49 views
1

大家好我有一個小的PHP問題:PHP刪除鏈接和內容

我有一個字符串許多這樣的:

$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); 

回答

7

它看起來恰到好處。

我只是嘗試這樣做,它似乎很好地工作:

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

嗨,我不想得到:嗨,我是一隻黑貓,所以我想得到:嗨,我是一隻貓 –

+0

是啊它的作品完美! –

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; 
+0

嗨,我不想讓: 您好我是一隻黑貓 ,所以我想: 你好我貓 –

+0

似乎不起作用 –

+0

@user什麼時候休息? – cwallenpoole