Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions to replace {{a,b}} and {{a}}

Tags:

regex

php

I have many strings. Some examples are shown below:

  1. This is my first example string. {{1}} This is what it looks like.
  2. This is my second example string. {{1,2}}. This is what it looks like.
  3. This is my third example string. {{1,3}} and {{2}}. This is what it looks like.

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}}

like image 761
Nikhil Agarwal Avatar asked Oct 31 '22 16:10

Nikhil Agarwal


1 Answers

Use regex \{\{(\d+)(,(\d+))?\}\}

Regex Explanation and Live Demo

  1. \{: Matches { literally, need to escape as it is special symbol in regex
  2. (\d+): Matches one or more digits, captured in group 1
  3. (,(\d+))?: Matches one or more digits followed by comma optionally
  4. \}: 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);
like image 91
Tushar Avatar answered Nov 15 '22 06:11

Tushar