lockdownd7 Posted August 31, 2009 Share Posted August 31, 2009 I need a function that works like str_replace, but lets me replace each instance of the string I'm finding with a different value. Something like this: str_replace($stringtobereplaced , $array[] , $filebeingsearched); Where the first instance would be replaced by $array[0], the second instance by $array[1], etc. Any ideas? Link to comment https://forums.phpfreaks.com/topic/172629-solved-advanced-str_replace/ Share on other sites More sharing options...
MadTechie Posted September 1, 2009 Share Posted September 1, 2009 Why not just create a loop with the array and use preg_replace with the replacement limit to 1 here's a basic concept (untested) $string = 'test test test test test test test test test test '; $find = '/test/i'; $replace = array('1','2','3','4','5'); foreach($replace as $R) { $string = preg_replace($find, $R, $string,1); } echo $string; expected output 1 2 3 4 5 test test test test test Link to comment https://forums.phpfreaks.com/topic/172629-solved-advanced-str_replace/#findComment-909958 Share on other sites More sharing options...
lockdownd7 Posted September 1, 2009 Author Share Posted September 1, 2009 Why not just create a loop with the array and use preg_replace with the replacement limit to 1 here's a basic concept (untested) $string = 'test test test test test test test test test test '; $find = '/test/i'; $replace = array('1','2','3','4','5'); foreach($replace as $R) { $string = preg_replace($find, $R, $string,1); } echo $string; expected output 1 2 3 4 5 test test test test test The string I'm replacing is a variable itself... how would I represent that with a regex? Link to comment https://forums.phpfreaks.com/topic/172629-solved-advanced-str_replace/#findComment-910021 Share on other sites More sharing options...
MadTechie Posted September 1, 2009 Share Posted September 1, 2009 like so $find = "Hello"; //your string $ifind = preg_quote($find, '/'); //$find = "/$ifind/i"; //case insensitive OR $ifind = "/$ifind/"; //case sensitive $replace = array('1','2','3','4','5'); foreach($replace as $R) { $string = preg_replace($ifind, $R, $string,1); } echo $string; Link to comment https://forums.phpfreaks.com/topic/172629-solved-advanced-str_replace/#findComment-910024 Share on other sites More sharing options...
lockdownd7 Posted September 1, 2009 Author Share Posted September 1, 2009 Thanks, works great! Link to comment https://forums.phpfreaks.com/topic/172629-solved-advanced-str_replace/#findComment-910031 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.