php - 在正则表达式中循环

标签 php regex pattern-matching iteration

正则表达式可以找到这个模式吗?

{{foo.bar1.bar2.bar3}}

组中的位置

$1 = foo $2 = bar1 $3 = bar2 $4 = bar3 and so on..

这就像一遍又一遍地重新执行表达式,直到无法匹配为止。

我正在研究的当前表达式是

(?:\{{2})([\w]+).([\w]+)(?:\}{2})

这是来自 regexr 的链接。

http://regexr.com?3203h

--

好吧,我想我没有很好地解释我在这里想要实现的目标。

假设我正在尝试替换所有

{{foo 内的

.barX 。 。 。 }}

我的预期结果应该是

$foo->bar1->bar2->bar3

最佳答案

假设匹配中不允许使用大括号,这应该可以工作:

preg_match_all(
    '%(?<=     # Assert that the previous character(s) are either
     \{\{      # {{
    |          # or
     \.        # .
    )          # End of lookbehind
    [^{}.]*    # Match any number of characters besides braces/dots.
    (?=        # Assert that the following regex can be matched here:
     (?:       # Try to match
      \.       #  a dot, followed by
      [^{}]*   #  any number of characters except braces
     )?        # optionally
     \}\}      # Match }}
    )          # End of lookahead%x', 
    $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];

关于php - 在正则表达式中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12191051/

相关文章:

php - 用户对数据库的存储过程访问被拒绝

php - Doctrine2 的 preUpdate 在 Symfony2 中缺少 PreUpdateEventArgs 参数

python - 我如何用 <div>$...$</div> 之类的东西替换 LaTeX $...$ 和 $$...$$ 符号?

arrays - 如何将数组强制转换为匹配臂中的切片?

syntax - 如何在 'let' 定义中使用模式匹配?

php - PHP 中的错误处理

php - 通知: Undefined index error in php

java - Java程序以在gradle构建文件中获取版本号

c# - Regex.Replace 在勉强匹配时有奇怪的行为

用于评估日期范围的正则表达式