【问题标题】:Create if/else variables and preg match/replace based on variable string根据变量字符串创建 if/else 变量和 preg 匹配/替换
【发布时间】:2019-03-01 03:32:14
【问题描述】:

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

例如{{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(非贪婪)和s(多行)解决了让 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];
  }
}

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

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

  • 如何在现场进行更换?

谢谢!

【问题讨论】:

  • s 多行点的模式修饰符。贪心匹配是个坏主意.*。多重条件声明是什么样的。你想如何匹配/避免它们?
  • @mickmackusa 多个条件位于顶部文本的第一位。客户可能希望为 DJ 指定不同的文本,为舞池指定不同的文本,并且仅在预订该服务时才显示该文本。不幸的是,多行的 s 导致它匹配第二个 {{endif}}
  • 它不是树枝,它是 saas 系统中的自定义变量(占位符)。我刚刚发现在预匹配中添加 U 会导致它“非贪婪”,并且 s 允许多行,我想我已经对多行问题进行了排序 - 只是没有替换文本。
  • 找到匹配项后使用preg_replace_callback 替换它们。
  • 是的,是的。

标签: php regex preg-replace preg-match


【解决方案1】:

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

  • 我正在使用\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", "$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

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

Demo

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

【讨论】:

  • 天哪,这么简单!我从没想过只是将服务名称插入到正则表达式中!!!谢谢!现在有没有办法删除 {{if|service_name=DJ Booth}}This is the text for DJs{{endif}} 因为它不匹配?
  • 好的,我会添加进去的。
  • 伴侣就是这样。我今天在这里学到了很多东西,尤其是用方括号加倍。非常感谢您的帮助!
  • 我还在纠结合并这两种模式。 regex101.com/r/y1mWvq/1 如果我想出更好的方法,我会联系你。我几乎满足:regex101.com/r/y1mWvq/2
猜你喜欢
  • 2020-04-06
  • 2020-04-28
  • 2013-02-16
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 2012-12-15
  • 2021-01-04
  • 1970-01-01
相关资源
最近更新 更多