fork(1) download
  1. <?php
  2.  
  3. $data = "<p class=\"title\">Title one</p>";
  4. $data .= "<p class=\"title\">Title two</p>";
  5. $data .= "<p class=\"title\">Title three</p>";
  6.  
  7. $reg = "/<p.*?class=[\"']*title[\"']*.*?>.*?<\/p.*?>/si";
  8.  
  9. $repl = "<p class=\"my\">Replace on two</p>";
  10.  
  11. echo $data, " -------> ";
  12.  
  13. $repl_counter = 0;
  14.  
  15. echo preg_replace_callback($reg, function($match) use (&$repl_counter, $repl)
  16. {
  17. $res = $match[0]; // default
  18. if ($repl_counter == 1) // second occurrence
  19. $res = $repl;
  20. $repl_counter++;
  21. return $res;
  22. }, $data);
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
<p class="title">Title one</p><p class="title">Title two</p><p class="title">Title three</p> -------> <p class="title">Title one</p><p class="my">Replace on two</p><p class="title">Title three</p>