首页 > 解决方案 > 根据变量字符串创建 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];
  }
}

哪个匹配正确,但只是将所有文本一起输出,而不是在它们匹配的同一个地方。

所以我的问题是....

谢谢!

标签: phpregexpreg-replacepreg-match

解决方案


通过在正则表达式模式中使用搜索变量,您可以定位所需的占位符。您不需要匹配/捕获搜索字符串,只需匹配它后面的文本。匹配整个占位符并将其替换为包含在条件语法中的捕获组。

  • \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);

推荐阅读