我必须限制用户在发送消息时遵循已定义的模板集。定义的模板也可以有占位符,用户可以在运行时替换它们。
如果消息与已预定义的模板匹配,我该如何检查。
// Predefined template
$template = 'Hi {{name}}, Hope you are enjoying our service. See you on {{date}}';
$template = 'Bank will remain closed on {{date}} on account of {{reason}}.';
用户可以编写这样的消息,该消息应与模板匹配
$message = 'Hi E, Hope you are enjoying our services. See you on 20th Jan';
$template = 'Bank will remain closed on 20th Jan on account of holiday.';
这将是一个无效的模板
$message = 'Hi E, Hope we are enjoying your services. See you on 20th Jan';
$template = 'Bank will remain open on 20th Jan on account of holiday.';
如何使用PHP中的预定义模板验证带有替换占位符的字符串?
答案 0 :(得分:1)
您可以使用.+?
代替{{wildcard}}
。这将允许任何字符,直到第一次出现下一个字符(和剩余的文本)。 .
是任何角色。 +
是前一个字符中的一个或多个。 ?
告诉+
在第一次出现时停止。 \
正在转义字符串中的特殊字符。前导和尾随/
是分隔符,指示正则表达式的开始和结束位置。
PHP用法:
$message[] = 'Hi E, Hope you are enjoying our services. See you on 20th Jan';
$template[] = 'Bank will remain closed on 20th Jan on account of holiday.';
$message[] = 'Hi E, Hope we are enjoying your services. See you on 20th Jan';
$template[] = 'Bank will remain open on 20th Jan on account of holiday.';
$templatem = '/Hi .+?, Hope you are enjoying our services\. See you on .+?/';
$templatet = '/Bank will remain closed on .+? on account of .+?\./';
foreach($message as $key => $mes) {
if(preg_match($templatem, $mes)) {
echo 'Match' . "\n";
} else {
echo 'No Match' . "\n";
}
if(preg_match($templatet, $template[$key])) {
echo 'Match' . "\n";
} else {
echo 'No Match' . "\n";
}
}
请注意,在您的第一个模板中,您有service.
,但在两个示例中,如果您希望services.
是可选的,则s
使用?
s
后shouldChangeCharactersInRange
}}
PHP演示:https://eval.in/501441
Regex101演示:https://regex101.com/r/cO2oD2/1