【问题标题】:Regexp lookahead and lookbehind and match between certain characters正则表达式前瞻和后视以及某些字符之间的匹配
【发布时间】:2015-03-13 10:55:33
【问题描述】:

目前我有这个正则表达式来检测双花括号之间的字符串,它的工作非常好。

$str = "{{test}} and {{test2}}";
preg_match_all('/(?<={{)[^}]*(?=}})/', $str, $matches);
print_r($matches);

Returns:
Array
(
[0] => Array
    (
        [0] => test
        [1] => test2
    )

)

现在我需要将其扩展为仅匹配 ]] 和 [[

之间的内容
$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";

我一直在尝试修改正则表达式,但前瞻和后瞻对我来说太难了。我怎样才能让它只匹配 ]] 和 [[ 里面的东西?

我还想匹配 ]] 和 [[ 之间的整个字符串,然后我想匹配其中 {{ }} 之间的每个单独的字符串。

例如:

$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";

Would return:
Array
(
[0] => Array
    (
        [0] => {{test}} and {{test2}}
        [1] => test
        [2] => test2
    )

)

【问题讨论】:

  • 请发布您使用的修改后的正则表达式
  • 好吧,它没有用,我尝试在 (?
  • 退后一步。您不能先与]]....[[ 匹配(您发布的正则表达式稍作修改)然后对第一个结果执行发布的正则表达式吗?
  • @unska 您的输入是否始终采用上述格式?

标签: php regex match


【解决方案1】:

使用preg_replace_callback

$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";
$arr = array();
preg_replace_callback('/\]\](.*?)\[\[/', function($m) use (&$arr) {
            preg_match_all('/(?<={{)[^}]*(?=}})/', $m[1], $arr); return true; }, $str);
print_r($arr[0]);

输出:

Array
(
    [0] => test
    [1] => test2
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 2020-02-04
    • 2019-05-09
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多