douhanzhuo6905 2015-11-11 18:10 采纳率: 100%
浏览 53
已采纳

使用preg_replace和FOR循环替换PHP关键字

I'm completely lost on what's wrong here. Any help will be appreciated.

I'm making a keyword replacement tool for a wordpress site. My problem is that my preg_replace seems to only run on the last element in the array when going through the post content.

The two get_options below are just textarea fields with each keyword and replacement on a separate line using character returns.

function keyword_replace($where) { 
  $keywords_to_replace = get_option('keywords_to_replace');
  $keyword_links = get_option('keyword_links');
  $KWs = explode("
", $keywords_to_replace);
  $URLs = explode("
", $keyword_links);

  $pattern = array(); 
  $replacement = array(); 
  for($i=0; $i< count($KWs); $i++) { 
    $pattern2 = '/<a[^>]*>(.*?)'.$KWs[$i].'(.*?)</a>/'; 
    if(preg_match($pattern2, $where))  {
      continue;
    } else {
      $pattern[$i] = '\'(?!((<.*?)|(<a.*?)))(\b'. $KWs[$i] . '\b)(?!(([^<>]*?)>)|([^>]*?</a>))\'si'; 
      $replacement[$i] .= '<a href="'.$URLs[$i].'" target="_blank">'.$KWs[$i].'</a>';
    }
  }
  return preg_replace($pattern, $replacement, $where, -1); 
} 
add_filter('the_content','keyword_replace');

A var_dump() returns all the correct information, and nothing appears to be skipped in the dump. I'm stuck trying to figure out why it doesn't loop through the whole array.

Thanks for your help, Rafael

  • 写回答

1条回答 默认 最新

  • doufan9805 2015-11-13 20:09
    关注

    I had a friend fix this for me. Just in case anyone else comes across a problem similar to mine, the fix was to use the trim() command around $KWs[$i] inside $pattern[$i].

    $pattern[$i] = '\'(?!((<.*?)|(<a.*?)))(\b'. trim($KWs[$i]) . '\b)(?!(([^<>]*?)>)|([^>]*?</a>))\'si';
    

    It all came down to windows vs. mac on character returns.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题