Pages

Friday, July 6, 2012

Replacing nth matching string using php

<?php
//Replacing nth matching string
$string = 'mugesh php programmer java programmer php java programmer php tester php is open source.';
$replaceme = 'php';
$replacewith = 'PHP5';
$nthtimes = 4;

echo preg_replace("/((.*?)(".$replaceme.")){".$nthtimes."}/e", '(preg_replace("/".$replaceme."$/", "", "\0")).$replacewith', $string); 
$result = preg_split("/({$replaceme})/",$string,$nthtimes,PREG_SPLIT_DELIM_CAPTURE);

array_push($result,preg_replace("/{$replaceme}/",$replacewith,array_pop($result),1));
echo implode($result); 

?>