Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all substring instances with a variable string

If you had the string

'Old string Old more string Old some more string'

and you wanted to get

'New1 string New2 more string New3 some more string'

how would you do it?

In other words, you need to replace all instances of 'Old' with variable string 'New'.$i. How can it be done?

like image 258
Marko Avatar asked Jul 06 '11 12:07

Marko


People also ask

How do you replace all occurrences of substring in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

Does string replace replace all instances?

The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.

Can you replace all occurrences?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')

How do you replace all instances of substring in Python?

replace() will replace all instances of the substring. However, you can use count to specify the number of occurrences you want to be replaced.


2 Answers

An iterative solution that doesn't need regular expressions:

$str = 'Old string Old more string Old some more string';
$old = 'Old';
$new = 'New';

$i = 1;

$tmpOldStrLength = strlen($old);

while (($offset = strpos($str, $old, $offset)) !== false) {
  $str = substr_replace($str, $new . ($i++), $offset, $tmpOldStrLength);
}

$offset in strpos() is just a little bit micro-optimization. I don't know, if it's worth it (in fact I don't even know, if it changes anything), but the idea is that we don't need to search for $old in the substring that is already processed.

See Demo

Old string Old more string Old some more string
New1 string New2 more string New3 some more string
like image 92
KingCrunch Avatar answered Sep 28 '22 18:09

KingCrunch


Use preg_replace_callback.

$count = 0;
$str = preg_replace_callback(
    '~Old~',
    create_function('$matches', 'return "New".$count++;'),
    $str
);
like image 33
Ilya Boyandin Avatar answered Sep 28 '22 18:09

Ilya Boyandin