一个正则替换:一段文本中有若干a img标记,替换文本中的某些词,不包含除了a img标记 中的文字、属性

如:

abcd</br>
cabcdef
<a href="">abcdef</a>
<img title="cabcdef"/>

  把纯文本中的abcd替换成xxxx

php方法

function _replace($matches)
{
  if($matches[1])return $matches[1];
  if($matches[2])return $matches[2];
  if($matches[3])return preg_replace("/abcd/","xxxx",$matches[3]);
}
echo preg_replace_callback(
    "/(<[^>]+>[^<]*<\/a>)|(<img.*\/>)|([^<]+)/",
    "_replace",
    $str
);

js方法

var re = //(<[^>]+>[^<]*<\/a>)|(<img.*\/>)|([^<]+)//gi;
s = s.replace(re, function(_, a, b) {
    return a ? a : b.replace(/abcd/g, 'xxxx');
});

  

谢谢@abcd提供的思路

posted @ 2013-05-30 13:26  acjialiren  阅读(211)  评论(0编辑  收藏  举报