【问题标题】:How to find variable text in string by using regex如何使用正则表达式在字符串中查找变量文本
【发布时间】:2019-05-03 09:02:05
【问题描述】:

我正在创建一个模板系统,它允许用户创建模板并使用原始字符串中的选定/动态值。

例子:

Original string:
Lorem ipsum dolor (Hello world) sit YEAH amet

Template:
consectetur adipiscing elit, sed do @BETWEEN("dolor (",") sit") eiusmod tempor incididunt ut labore et dolore @BEWTEEN("sit","amet")

Output:
consectetur adipiscing elit, sed do Hello world eiusmod tempor incididunt ut labore et dolore YEAH

我正在尝试使用正则表达式从模板中获取@BETWEEN

@BETWEEN\([^\(\)]+\)

但由于@BETWEEN 括号中的括号符号,它不起作用。 我不太擅长正则表达式。谁能给我关于如何增强正则表达式或任何其他方法以从模板中获取 @BETWEEN 函数的建议

【问题讨论】:

  • 避免使用正则表达式处理嵌套内容。
  • 根据您的模板,不应发生替换,因为原始字符串中 dolor () sit 之间没有值
  • 是的,这个例子好像错了。
  • @thehennyy 你没有义务在字符类[] 中转义
  • 很抱歉忘记了示例中的转义特殊字符。但即使逃脱了特殊字符,它仍然无法正常工作。

标签: php regex pcre


【解决方案1】:

因为您的模板模式会查找用引号括起来的字符串,例如"dolor (",您可以找到这些值,从中创建一个正则表达式来查找原始字符串中的匹配字符串,然后使用该匹配项将模板中的模式替换为原始字符串中的值。

$string = 'Lorem ipsum dolor (Hello world) sit YEAH amet';
$template = 'consectetur adipiscing elit, sed do @BETWEEN("dolor (",") sit") eiusmod tempor incididunt ut labore et dolore @BETWEEN("sit","amet")';

preg_match_all('/@BETWEEN\("([^"]+)","([^"]+)"\)/', $template, $matches, PREG_SET_ORDER);
foreach ($matches as $temp) {
    $regex = '/' . preg_quote($temp[1]) . '(.*?)' . preg_quote($temp[2]) . '/';
    preg_match($regex, $string, $replacement);
    $template = preg_replace('/' . preg_quote($temp[0]) . '/', $replacement[1], $template);
}
echo $template;

输出:

consectetur adipiscing elit, sed do Hello world eiusmod tempor incididunt ut labore et dolore YEAH 

请注意,如果您的模板模式中的字符串还包含转义引号,这将不起作用。在这种情况下,要实现此功能,您需要使用派生自 this question 之类的正则表达式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-17
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2011-06-11
    相关资源
    最近更新 更多