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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题