php - 根据变量字符串创建 if/else 变量和 preg 匹配/替换
问题描述
我有一个文本区域,我们的用户可以用真实的订单数据替换变量。
例如{{service_name}}
将替换为“DJ Booth”
现在我正在创建基于服务名称显示某些文本的能力。例如...
Some text at the start
{{if|service_name=DJ Booth}}
This is the text for DJs
{{endif}}
Some text in the middle
{{if|service_name=Dancefloor Hire}}
This is the text for dancefloor hire
{{endif}}
Some text at the end
U
使用(non greedy) 和s
(multi line)解决了让 preg_match 在多行上工作
所以现在的输出是......
问题是可能有多个条件,所以我不能只匹配类型然后打印值,因为我需要遍历每个匹配,并替换匹配的文本而不是在底部输出。
所以我正在使用这个...
$service = get_service();
preg_match_all("/{{if\|service=(.*)}}(.*){{endif}}/sU", $text, $matches);
$i=0;
foreach($matches[1] as $match) {
if ($match == $service) {
print $match[2][$i];
}
}
哪个匹配正确,但只是将所有文本一起输出,而不是在它们匹配的同一个地方。
所以我的问题是....
- 我如何让更换发生在原地?
谢谢!
解决方案
通过在正则表达式模式中使用搜索变量,您可以定位所需的占位符。您不需要匹配/捕获搜索字符串,只需匹配它后面的文本。匹配整个占位符并将其替换为包含在条件语法中的捕获组。
- 我
\R
用来匹配换行符。 - 我
\s
用来匹配所有空格。 s
是.
匹配任何字符(包括换行符)的模式修饰符。- 匹配捕获组之外的
\s
和\R
字符允许替换文本很好地与相邻文本一致。
代码:(演示)
$text = 'Some text at the start
{{if|service_name=DJ Booth}}
This is the text for DJs
{{endif}}
Some text in the middle
{{if|service_name=Dancefloor Hire}}
This is the text for dancefloor hire
{{endif}}
Some text at the end';
$service = "Dancefloor Hire";
echo preg_replace("/{{if\|service_name=$service}}\s*(.*?)\R{{endif}}/s", "$1", $text);
输出:
Some text at the start
{{if|service_name=DJ Booth}}
This is the text for DJs
{{endif}}
Some text in the middle
This is the text for dancefloor hire
Some text at the end
扩展:如果要清除所有不合格的占位符,请执行第二遍并删除所有剩余的占位符。
echo preg_replace(["/{{if\|service_name=$service}}\s*(.*?)\R{{endif}}/s", "/\R?{{if.*?}}.*?{{endif}}\R?/s"], ["$1", ""], $text);
推荐阅读
- charts - Flutter 图表 PanAndZoomBehavior 不在手势中心缩放
- hyperledger-fabric - 为超级账本网络实施分布式分布式账本
- java - 按下按钮使线程完成工作
- javascript - ag-grid 自定义过滤器添加了清除过滤器按钮。JS 不是 Angular
- javascript - 使用javascript自动填充输入
- javascript - 当我使用特定的 dateTime 格式时,使用 CanvasJS 的图形为空
- python - 在拼写检查程序中引起注意包装问题
- artifactory - Artifactory Pro 升级
- scala - 来自光滑生成模式的表列表
- javascript - 在 Apple HomeKit 中使用 Node-Red 将电源使用情况显示为温度