对于特定的模板引擎,用户将在其中添加/更新模板以向客户发送消息。
我正在使用正则表达式来验证每个模板文字都有双标签,一个字符串中的开始<<和结束>>标签。
Given 是有效的模板引擎。
Hi <<cName>>, please make your payment of $ <<totAmt>>
for Account number <<accNum>> given by <<agentName>> at this link <<payLink>>
The validity of this link is 30 minutes.
给定的是valid 模板文字
<<cName>>
<<totAmt>>
<<accNum>>
<<agentName>>
<<payLink>>
给定的是invalid 模板文字
<<cName>
<<agentName>>>>>>>>
<cName>
<<<<<payLink>>
<<cName<<>>
目前给是我的解决方法。
首先,我使用给定的正则表达式获取所有模板文字。
<.*?>(?!>)
然后遍历每个文字以在 PHP 中使用给定的正则表达式进行验证。如果任何文字无效,则用户更新的给定模板无效。
^<{2}[^<>]+>{2}(?!>)
$is_tpl_valid = true; //template is valid
$template = 'Hi <<cName>>, please make your payment of $ <<totAmt>>
for Account number <<accNum>> given by <agentName>> at this link <<payLink>>
The validity of this link is 30 minutes.';
echo '<br/> --- File: ' . __FILE__ . '#'. __LINE__ . '------- $template -> ' . $template . ' --------------<br/>';
if(preg_match_all('#<.*?>(?!>)#', $template, $matched))
{
echo '<pre>';
print_r($matched);
foreach($matched[0] as $item)
{
if($is_tpl_valid && !preg_match('#^<{2}[^<>]+>{2}(?!>)#', $item))
{
echo '<br/> --- File: ' . __FILE__ . '#'. __LINE__ . '------- $item -> ' . $item . ' --------------<br/>';
$is_tpl_valid = false; //template is invalid
}
}
}
我们可以在单个正则表达式或任何更好的解决方案(在 JS / PHP 中)中找到无效的模板文字。
提前致谢