2011-07-21 74 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解析器而不是