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);
?>

Link to comment
Share on other sites

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');

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.