2011-07-21 109 views
0

如何使用preg_replace,使用class="country"刪除所有鏈接並保留鏈接的文本。php preg_replace

<a href="XXXXXX" class="country">TEXT</a> => TEXT

如何修改下面的preg_replace

$str = <<<EOT 
Long long ago, there was a poor boy named <a href="index1.html">John</a>. Who was living in <a href="index2.html">Liverpoor</a>, a city of <a href="index3.html" class="country">england</a>. 
EOT; 
$result= preg_replace('/<a(.*?)class="country"(.*?)>(.*?)<\/a>/i','$3',$str); 
echo $result; 
// I want get the result as: "Long long ago, there was a poor boy named <a href="index1.html">John</a>. Who was living in <a href="index2.html">Liverpoor</a>, a city of england" 
+0

它看起來像你得到你想要的東西。 '英格蘭'是應該刪除的唯一鏈接文本。 – Nik

+0

@Nik,不,我的代碼破壞了所有的鏈接。我仍然想保持其他鏈接,只是斷開'class =「country」'的鏈接 –

回答

0

這將大多數情況下工作:

$result= preg_replace('/<a [^>]*class="country"[^>]*>([^<]+)<\/a>/i','$1',$str); 

但請考慮使用DOM解析器而不是