Jump to content


Photo

Replacing third string occurance within a larger string


  • Please log in to reply
1 reply to this topic

#1 dagnasty

dagnasty
  • Members
  • PipPipPip
  • Advanced Member
  • 66 posts

Posted 10 July 2006 - 04:28 AM

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 example

1st string: dog cat bird owl cat bird cat elephant
2st string bird cat dog cat cat dog elephant

what would I do?

#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,025 posts

Posted 10 July 2006 - 06:46 AM

One way

<?php
function 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>';
?>

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users