title: PHP preg_match multiple occurence & multipe uses on same page
body: <p>I have created a CSV file containing two columns, one with a list of keywords separated by a | and another one with a URL.</p>
  
  <p>What I'm trying to do with this file is to find the keywords in my blog articles and replace plain text by links pointing to the URL from the CSV file. The final goal is to increase SEO performance on some keywords.</p>
  
  <p>I'm using the following code:</p>
  
  <pre><code>foreach ($links as $key=&gt;$value)
          {
              $url=$value["url"];
              $pattern="#&lt;p.*?&gt;(.*)\ (".$value["keyword"].")\ (.*)&lt;/p&gt;#";
              $content=preg_replace($pattern,"$1 &lt;a href=\"".$url."\"&gt;$2&lt;/a&gt; $3",$content);
          }
  </code></pre>
  
  <p>$links is an array containing the content of the CSV file, it has a key containing the keyword(s) and a key containing the URL. </p>
  
  <p>Example</p>
  
  <pre><code>$value["keyword"] contains keyword1|keyword2
  $value["url"] contains the url to point to
  $content contains the article
  </code></pre>
  
  <p>The code mentioned here above works but not exactly how I would like it to work. For one given keyword, it doesn't replace all occurrences of that keyword. Some keywords are not replaced at all. There must be something wrong with the regular expression but I don't see directly where.</p>
  
  <p><strong>In the end, what I would like to:</strong></p>
  
  <ul>
  <li>replace a keyword by a link</li>
  <li>limit the amount of times a keyword is replaced to avoid having links all over the article (ex: replace the two first two occurences)</li>
  <li><p>apply the preg_replace at page load because I'm going to change the keyword list regularly to find the most efficient keyword combination</p>
  
  <ul>
  <li>avoid affecting page load performance</li>
  <li>I'm using Wordpress and don't want to use an external plug-in</li>
  </ul></li>
  </ul>
  
  <p><strong>So in a nutshell my questions are:</strong></p>
  
  <ul>
  <li>how could I transform the regular expression so that all keywords are being replaced with a maximum of X times</li>
  <li>how can I ensure that this preg_match doesn't decrease my page performance</li>
  </ul>
  
  <p>Any idea ?</p>
  
  <p>Thanks a lot!</p>
  
  <p>Laurent</p>