Replace all instances of a substring with a variable string

If you had a line

'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 that?

In other words, you need to replace all instances of "Old" with the string variable "New". $ i. Any suggestions?

+6
source share
5 answers

An iterative solution that does not 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 small micro-optimization. I donโ€™t know if itโ€™s worth it (in fact, I donโ€™t even know if it changes something), but the idea is that we do not need to look for $old in the substring, that is, are already being processed.

See Demo

 Old string Old more string Old some more string New1 string New2 more string New3 some more string 
+6
source

Use preg_replace_callback .

 $count = 0; $str = preg_replace_callback( '~Old~', create_function('$matches', 'return "New".$count++;'), $str ); 
+2
source

What about:

 $str = 'Old string Old more string Old some more string'; $i = 1; while (preg_match('/Old/', $str)) { $str = preg_replace('/Old/', 'New'.$i++, $str, 1); } echo $str,"\n"; 

exit:

 New1 string New2 more string New3 some more string 
+1
source

I had the same solution as KingCrunch, but as he already answered, I was interested in the str_replace with a callback for replacements and came up with this ( Demo ):

 $subject = array('OldOldOld', 'Old string Old more string Old some more string'); $search = array('Old', 'string'); $replace = array( function($found, $count) {return 'New'.$count;}, function($found, $count) {static $c=0; return 'String'.(++$c);} ); $replace = array(); print_r(str_ureplace($search, $replace, $subject)); /** * str_ureplace * * str_replace like function with callback * * @param string|array search * @param callback|array $replace * @param string|array $subject * @param int $replace_count * @return string|array subject with replaces, FALSE on error. */ function str_ureplace($search, $replace, $subject, &$replace_count = null) { $replace_count = 0; // validate input $search = array_values((array) $search); $searchCount = count($search); if (!$searchCount) { return $subject; } foreach($search as &$v) { $v = (string) $v; } unset($v); $replaceSingle = is_callable($replace); $replace = $replaceSingle ? array($replace) : array_values((array) $replace); foreach($replace as $index=>$callback) { if (!is_callable($callback)) { throw new Exception(sprintf('Unable to use %s (#%d) as a callback', gettype($callback), $index)); } } // search and replace $subjectIsString = is_string($subject); $subject = (array) $subject; foreach($subject as &$haystack) { if (!is_string($haystack)) continue; foreach($search as $key => $needle) { if (!$len = strlen($needle)) continue; $replaceSingle && $key = 0; $pos = 0; while(false !== $pos = strpos($haystack, $needle, $pos)) { $replaceWith = isset($replace[$key]) ? call_user_func($replace[$key], $needle, ++$replace_count) : ''; $haystack = substr_replace($haystack, $replaceWith, $pos, $len); } } } unset($haystack); return $subjectIsString ? reset($subject) : $subject; } 
+1
source

From the PHP manual on str_replace :

Replace all occurrences of the search string with a replacement string

 mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) 

Search

Distortion of meaning, otherwise called a needle . An array can be used to indicate multiple needles.

replace

A replacement value that replaces the found search values. An array can be used to indicate several replacements.

Headline

A string or array, search and replace, otherwise known as haystack .

If the object is an array, then the search and replace is performed with each record of the object, and the return value is also an array.

number

If passed, it will be set to the number of replacements completed.

0
source

Source: https://habr.com/ru/post/892134/


All Articles