Jump to content

Regular Expressions


MrAdam

Recommended Posts

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

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...