我有很多字符串。下面显示了一些示例:
- 这是我的第一个示例字符串。 {{1}} 这就是它的样子。
- 这是我的第二个示例字符串。 {{1,2}}。这就是它的样子。
- 这是我的第三个示例字符串。 {{1,3}} 和 {{2}}。这就是它的样子。
我的代码需要替换每个看起来像 {{1}}
的标记与 <input name="var1">
它还需要替换每个看起来像 {{1,2}}
的标记与 <input name="var1" value="2">
一般来说,每个看起来像 {{a}}
的标记需要替换为<input name="vara">
每个标记看起来像 {{a,b}}
与 <input name="vara" value="b">
我正在使用 php。
执行此操作的最佳方法是什么。每个字符串中将有许多要替换的“标记”。每个字符串都可以有两种样式的标记。
现在,我的代码如下所示:
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);
}
但这显然不是很有效,因为我循环查找匹配项。当然,我什至不匹配看起来像 {{1,2}}
的标记
最佳答案
使用正则表达式 \{\{(\d+)(,(\d+))?\}\}
Regex Explanation and Live Demo
\{
:字面上匹配{
,需要转义,因为它是正则表达式中的特殊符号(\d+)
:匹配一个或多个数字,在第 1 组中捕获(,(\d+))?
:匹配一个或多个数字后跟可选的逗号\}
:按字面意思匹配
$1
和 $3
用于替换,分别得到第一个和第三个捕获组。
示例代码用法:
$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);
关于php - 替换 {{a,b}} 和 {{a}} 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33537732/