包子

木森技术分享

路漫漫其修远兮,吾将上下而求索。

您现在的位置是:网站首页 > PHP

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

2022-04-19 16:15:37364

  如:

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');
});