title: str_replace with limit argument
body: <p>Oh boy this is a doozy. Well I have an array of images in an array with key value.</p>
  
  <pre><code>$smiles = array( ':)' =&gt; 'http://www.example.com/happy.png', ':(' =&gt; 'http://www.example.com/sad.png' );
  </code></pre>
  
  <p>and then I have a text input: <code>that's sad to hear :(, but also great that you go a new dog :)</code></p>
  
  <p>I'm can parse the whole array and replace using the str_replace, but I want a limit of 4 smilies per message.</p>
  
  <p>my old one (no limit):</p>
  
  <pre><code>function addSmilies($text){
      global $smilies;
  
      foreach($smilies as $key =&gt; $val)
      {
          $search[] = $key;
          $replace[] = '&lt;img src="' . $val . '" alt="' . $key . '" /&gt;';
      }
  
      $text = str_replace( $search, $replace, $text );
      return $text;
  }
  </code></pre>
  
  <p>I understand you can use preg_replace, and that has a limit but I'm horrid with regex and can't get them to do what I want. So back to my question. Is there a str_replace with a limit that works with arrays or should I stick to preg_replace?</p>
  
  <p>UPDATE: I thought about stripping the :) and :( first before I replace with actual  markup.</p>
  
  <pre><code>function addSmilies($text){
      global $smilies;
  
      foreach($smilies as $key =&gt; $val)
      {
          $search[] = $key;
          $replace[] = '&lt;img src="' . $val . '" alt="' . $key . '" /&gt;';
      }
  
      $limit = 4;
      $n = 1;
  
      for($i=0; $i&lt;count($search); $i++)
      {
          if($n &gt;= $limit)
              break;
  
          if(strpos($text, $search[$i]) === false)
              continue;
  
          $tis = substr_count( $text , $search[$i] ); //times in string
          $isOver = ( $n + $tis &gt; $limit) ? true : false;
          $count = $isOver ? ($limit - $n) : $tis;
  
          $f = 0;
          while (($offset = strpos($text, $search[$i])) !== false)
          {
              if($f &gt; $count)
                  $text = substr_replace($text, "", $offset, strlen($search[$i]));
              $f++;
          }
  
          $n += $tis;
      }
  
      $text = str_replace( $search, $replace, $text );
  
      return $text;
  }
  </code></pre>
  
  <p>but now no images will show at all!?</p>