[英]regex php, match string with variable text (letters, numbers, underscore, [])
I am building a simple template engine (in PHP) and I need regex for my loop code, the loop should look something like this: 我正在构建一个简单的模板引擎(在PHP中),我的循环代码需要正则表达式,循环应该如下所示:
{loop var=menu[0]}
<li><a href="{link}">{text}</a></li>
{/loop}
where "menu[0]" can be any string of uppercase or lowercase letters with/without underscores, numbers and box parentheses ([]) 其中“menu [0]”可以是任何带有/不带下划线,数字和方括号([])的大写或小写字母的字符串
the '{loop var=', '}' and '{/loop}' always stay the same
I'll be using php's preg_match to make the comparison. 我将使用php的preg_match进行比较。
my regex so far (which is probably wildly off) is: 到目前为止,我的正则表达式(可能很大程度上是关闭的)是:
/[{loop var=][\w\s_0-9\[\]][}]/
my php is something like this: 我的PHP是这样的:
function loop($template) {
preg_match($pattern, $template, $matches);
foreach ($matches as $key => $match) {
...
$var = str_replace(array('{loop var=', '}'), '', $match));
$data = $this->get($var);
...
$loop_code = str_replace('{' . $var . '}', $data, $loop_code);
...
}
}
the input is my template above, the desired output is below 输入是我上面的模板,所需的输出如下
<ul>
<li><a href="<?php print $menu[0][0]['link']; ?>"><?php print $menu[0][0]['text']; ?></a></li>
<li><a href="<?php print $menu[0][1]['link']; ?>"><?php print $menu[0][1]['text']; ?></a></li>
</ul>
to do this I need preg_match to match any of these strings (in their entirity) 要做到这一点,我需要preg_match来匹配任何这些字符串(在他们的整体)
{loop var=menu[0]}
{loop var=menu_main}
{loop var=__menu}
{loop var=MenuMain}
Thank you for any input. 谢谢你的任何意见。
I'm not sure if this is exactly what you're after but the following regular expression will match any of the 4 examples you have provided after the = and before the closing } 我不确定这是否正是您所追求的,但以下正则表达式将匹配您在=之后和结束之前提供的4个示例中的任何一个
$replacement = '/(menu\[\d]|(m|M)enu(_)?(m|M)ain|__menu))/';
I'm just not too sure how you want to use it and what you are going to replace it with. 我不太确定你想如何使用它以及你要用它替换它。
If you also want to capture the {loop var=xxxxx } You'll need this: 如果你还想捕获{loop var = xxxxx}你需要这个:
$replacement = '//({loop var=(menu\[\d]|(m|M)enu(_)?(m|M)ain|__menu)})/';
You're misusing square brackets, which indicate only a single character . 你滥用方括号,它只表示一个字符 。 Try using a resource such as http://regex101.com/ to test things out. 尝试使用http://regex101.com/等资源进行测试。
Rather than mucking with str_replace
to clean things up afterward, just use the full power of preg_match()
: 而不是使用str_replace
来清理事后,只需使用preg_match()
的全部功能:
$template = "{loop var=menu[0]}\n<li><a href=\"{link}\">{text}</a></li>\n{/loop}";
$pattern = "/\{loop var=([\w\[\]]+)\}(.*?)\{\/loop\}/ism";
preg_match($pattern, $template, $matches);
$var_name = $matches[1];
$template_code = $matches[2];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.