如:
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提供的思路