Jump to content

Replace all occurrences but the first


The Little Guy

Recommended Posts

try[code[<?php
function my_replace($srch, $replace, $subject, $skip=1){
    $subject = explode($srch, $subject.' ', $skip+1);
    $subject[$skip] = str_replace($srch, $replace, $subject[$skip]);
    while (($tmp = array_pop($subject)) == '');
    $subject[]=$tmp;
    return implode($srch, $subject);
}
$test ='bla bla sasa bla bla sasa bla bla sasa';
echo my_replace('sasa', 'xxx', $test);
echo "<br />\n";
echo my_replace('sasa', 'xxx', $test, 2);
?>

Here's my take:

 

function replace_skip($str, $find, $replace, $skip = 1) {
$cpos = 0;
for($i = 0, $len = strlen($find);$i < $skip;++$i) {
	if(($pos = strpos(substr($str, $cpos), $find)) !== false) {
		$cpos += $pos + $len;
	}
}
return substr($str, 0, $cpos) . str_replace($find, $replace, substr($str, $cpos));
}

$str = 'test gfjgfjg test fdhsghg test test test';
echo replace_skip($str, 'test', 'xxxx');

Here's my take, works (mostly) like preg_replace (same as first 3 params of preg_replace) but with an additional argument to specify how many to skip.

 

function preg_replace_skip($pattern,$replace,$subject,$skip=0) {
  return preg_replace_callback(
    $pattern,
    create_function(
      '$m',
      'static$s;$s++;return($s<='.$skip.')?$m[0]:"'.$replace.'";'
    ),
    $subject
  );
} // end preg_replace_skip

 

 

Example 1: case sensitive, skip first match

$pattern = '~test~';
$replacement = '[x]';
$subject = 'blah blah Testblah blahblah test test blah';

echo preg_replace_skip($pattern,$replacement,$subject,1);
// before: blah blah Testblah blahblah test test blah
//  after: blah blah Testblah blahblah test [x] blah 

 

 

Example 2: case insensitive, skip first two matches

$pattern = '~test~i';
$replacement = '[x]';
$subject = 'blah blah Testblah blahblah test test blah';

echo preg_replace_skip($pattern,$replacement,$subject,2);
// before: blah blah Testblah blahblah test test blah
//  after: blah blah Testblah blahblah test [x] blah

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.