dagnasty Posted July 10, 2006 Share Posted July 10, 2006 I need to be enlightened of a function or a way to replace the third occurance of a string within a larger string. For example, if I wanted to replace the third occurance of "cat" within each string, For example1st string: dog cat bird owl cat bird cat elephant2st string bird cat dog cat cat dog elephantwhat would I do? Link to comment https://forums.phpfreaks.com/topic/14140-replacing-third-string-occurance-within-a-larger-string/ Share on other sites More sharing options...
Barand Posted July 10, 2006 Share Posted July 10, 2006 One way[code]<?phpfunction replaceNth ($s, $r, $str, $n) { // args : search, replace, string, N $l = strlen($s); $pos = 0; for ($i=0; $i<$n; $i++) { if (($pos = strpos($str,$s,$pos))===false) { return $str; } $pos += $l; } return substr_replace($str, $r, $pos-$l, $l);}// Test it$search = 'cat';$replace = 'tiger';$str = array('dog cat bird owl cat bird cat elephant', 'bird cat dog cat cat dog cat elephant', 'bird cat dog cat dog elephant', 'bird cat dog cat dog cat'); foreach ($str as $x) echo $x, '<br>', replaceNth($search, $replace, $x, 3),'<br><br>';?>[/code] Link to comment https://forums.phpfreaks.com/topic/14140-replacing-third-string-occurance-within-a-larger-string/#findComment-55417 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.