MrAdam Posted January 7, 2008 Share Posted January 7, 2008 Hello. I've been racking my brain for hours trying to work out how, if it's possible, to basically search for every instance of say... {VAR} and replace each instance respectively with a value stored in an array, using regular expressions.So for example I have an array like... $replacements[0]='first instance';$replacements[1]='second instance'; Could anybody help?Cheers! Adam Link to comment Share on other sites More sharing options...
Synook Posted January 10, 2008 Share Posted January 10, 2008 Not possible with regular expressions. You will need to use a loop in conjunction with other string functions, e.g. $string = "Your string ready for replacement";$needle = "{VAR}";$replacements = array("first instance", "second instance");$caret = 0;while (strpos($string, $needle)) {$pos = strpos($haystack, $needle);$former = substr($string, 0, $pos);$latter = substr($string, $pos + strlen($needle));$string = $former . $replacements[$caret] . $latter;if ($caret == count($replacements) - 1) $caret = 0; else $caret++;} Th[e revised edition below] should work. Link to comment Share on other sites More sharing options...
MrAdam Posted January 10, 2008 Author Share Posted January 10, 2008 Looks good man cheers. Just one question though, where does $haystack come from? Adam Link to comment Share on other sites More sharing options...
Synook Posted January 14, 2008 Share Posted January 14, 2008 Oops sorry - revised (correct) edition $string = "Your string ready for replacement";$needle = "{VAR}";$replacements = array("first instance", "second instance");$caret = 0;while (strpos($string, $needle)) {$pos = strpos($string, $needle);$former = substr($string, 0, $pos);$latter = substr($string, $pos + strlen($needle));$string = $former . $replacements[$caret] . $latter;if ($caret == count($replacements) - 1) $caret = 0; else $caret++;} Link to comment Share on other sites More sharing options...
MrAdam Posted January 14, 2008 Author Share Posted January 14, 2008 course yeah... al give it a whirl. cheers for the help! Adam Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.