Jump to content
MrAdam

Regular Expressions

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

Share this post


Link to post
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.

Share this post


Link to post
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++;}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×