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.

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?