我有很多弦。一些示例如下所示:
我的代码需要更换每个标记,看起来像{{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+))?\}\}
\{
:{
从字面上匹配,需要转义,因为它是正则表达式中的特殊符号(\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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句