创建 if/else 个变量并根据变量字符串 preg match/replace

Create if/else variables and preg match/replace based on variable string

我有一个文本区域,我们的用户可以在其中用实际订单数据替换变量。

例如{{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

让 preg_match 在多行上工作已通过 U(非贪婪)和 s(多行)

解决

所以现在的输出是....

问题是可能有多个条件,所以我不能只预匹配类型然后打印值,因为我需要遍历每个匹配,并替换匹配的文本而不是输出底部。

所以我正在使用这个...

$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];
  }
}

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

所以我的问题是......

谢谢!

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

  • 我正在使用 \R 来匹配换行符。
  • 我正在使用 \s 来匹配所有空格。
  • s 是使 . 匹配包括换行符在内的任何字符的模式修饰符。
  • 匹配捕获组外的 \s\R 字符允许替换文本与相邻文本很好地一致。

代码:(Demo)

$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", "", $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

扩展:如果要擦除所有不合格的占位符,请执行第二遍并删除所有剩余的占位符。

Demo

echo preg_replace(["/{{if\|service_name=$service}}\s*(.*?)\R{{endif}}/s", "/\R?{{if.*?}}.*?{{endif}}\R?/s"], ["", ""], $text);