Php 多次匹配同一图案

Php 多次匹配同一图案,php,regex,Php,Regex,我有一个字符串,其结构如下: ~ foo; text 1 ~ foo; text 2 ~ foo; ... ~ foo; text n ~ foo; 我正在尝试获取文本1,文本2。。文本n放入一个数组,但我不知道该怎么做,所以我的问题是:如何将这些信息放入数组? 我尝试了以下正则表达式:~\s*([a-z0-9]+)\s*(;|\r |\r\n)([^~]*)~\s*\\1!我,但它似乎只与第一次出现的匹配。(我试过了) **更新:示例:** 我的字符串: // .. text before.

我有一个字符串,其结构如下:

~ foo;
text 1
~ foo;
text 2
~ foo;
...
~ foo;
text n
~ foo;
我正在尝试获取
文本1,文本2。。文本n
放入一个数组,但我不知道该怎么做,所以我的问题是:如何将这些信息放入数组?

我尝试了以下正则表达式:
~\s*([a-z0-9]+)\s*(;|\r |\r\n)([^~]*)~\s*\\1!我
,但它似乎只与第一次出现的匹配。(我试过了)

**更新:示例:**

我的字符串:

// .. text before... //
~ Key; 
  some random text
~ Key;
  another random text
~ Key;

// .. some random text .. //

~ Key2; some random text again
~ Key2; 
another some random text again
~ Key2;
Array
(
    [Key] => Array
        (
            [0] => some random text
            [1] => another some random text
        )

    [Key2] => Array
        (
            [0] => some radom text again
            [1] => another some radom text again
        )

)
并且输出应为:

// .. text before... //
~ Key; 
  some random text
~ Key;
  another random text
~ Key;

// .. some random text .. //

~ Key2; some random text again
~ Key2; 
another some random text again
~ Key2;
Array
(
    [Key] => Array
        (
            [0] => some random text
            [1] => another some random text
        )

    [Key2] => Array
        (
            [0] => some radom text again
            [1] => another some radom text again
        )

)

它不需要完全使用正则表达式来完成,您必须继续使用
preg\u match\u all
,因为老实说,这是您需要的工具

原因是它执行一个全局搜索,这正是您在说以下内容时所表达的要求:

“但它似乎只匹配第一次出现的情况。”

这就是“预匹配”的目的


无论如何,正则表达式的问题在于反向引用
\1

当您捕获
text 1
时,它会继续查找
text 1
,而不是您希望的
text\d


如果您能提供更真实的数据示例,我可以为其创建一个表达式。

使用preg\u replace\u回调获得whished结构的原始方法:

$pattern = '/^~ (\w+);\s*(.+?)\s*(?=\R~ \1;)/ms';
$res = array();

preg_replace_callback($pattern,
                      function ($m) use (&$res) { $res[$m[1]][] = $m[2]; },
                      $str);

print_r($res);
注意:我假设“随机文本”可以是多行的,如果不是这样,您可以将模式更改为
/^(\w+)\h*\R?\h*(\N+?)\h*(?=\R~\1;)/m

\R
是包含任何类型换行符的原子组的快捷方式。

\N
匹配除换行符以外的所有字符,无论是哪种模式(单线还是非单线)

文本后总是1,2,3,4,5,6,…N吗?@John是
foo
动态的?@John我现在有点太懒/太累了,无法发布完整的答案并进行解释,所以请继续。@HamZa真棒!它按预期工作!非常感谢。