I have many strings. Some examples are shown below:
My code needs to replace each token that looks like {{1}}
with <input name="var1">
It also needs to replace each token that looks like {{1,2}}
with <input name="var1" value="2">
In general, each token that looks like {{a}}
needs to be replaced with <input name="vara">
and each token that looks like {{a,b}}
with <input name="vara" value="b">
I am using php.
What would be the best way to do this. There will be many "tokens" to replace within each string. And each string can have tokens of both styles.
Right now, my code looks like this:
for ($y = 1; $y < Config::get('constants.max_input_variables'); $y++) {
$main_body = str_replace("{{" . $y . "}}", "<input size=\"5\" class=\"question-input\" type=\"text\" name=\"var" . $y . "\" value=\"".old('var'.$y)."\" >", $main_body);
}
But this is obviously not very efficient since I cycle through looking for matches. And ofcourse, I am not even matching the tokens that look like {{1,2}}
Use regex \{\{(\d+)(,(\d+))?\}\}
Regex Explanation and Live Demo
\{
: Matches {
literally, need to escape as it is special symbol in regex(\d+)
: Matches one or more digits, captured in group 1(,(\d+))?
: Matches one or more digits followed by comma optionally\}
: Matches }
literally$1
and $3
are used in the replacement to get the first and third captured group respectively.
Example Code Usage:
$re = "/\\{\\{(\\d+)(,(\\d+))?\\}\\}/mi";
$str = "This is my first example string. {{1}} This is what it looks like.\nThis is my second example string. {{1,2}}. This is what it looks like.\nThis is my third example string. {{1,3}} and {{2}}. This is what it looks like.";
$subst = "<input name=\"var$1\" value=\"$3\" />";
$result = preg_replace($re, $subst, $str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With