PHP keyword replacement using preg_replace and a FOR loop

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.

Read More

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("n", $keywords_to_replace);
  $URLs = explode("n", $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

Related posts

1 comment

  1. 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.

Comments are closed.