PHP从正则表达式获取数组

pie*_*e6k 1 php regex

我有字符串

$content = "Some content some content
[images ids="10,11,20,30,40"]
Some content";
Run Code Online (Sandbox Code Playgroud)

我想从中删除[images ids="10,11,20,30,40"]部分并获取id作为phparray(10,11,20,30,40)

正则表达式有可能吗?

Cas*_*yte 6

你可以用这个:

$txt = <<<LOD
Some content some content
[images ids="10,11,20,30,40"]
Some content
LOD;

$result = array();

$txt = preg_replace_callback('~(?:\[images ids="|\G(?<!^))([0-9]+)(?:,|"])~',
    function ($m) use (&$result) { $result[] = $m[1]; }, $txt);

echo $txt . '<br>' . print_r($result, true);
Run Code Online (Sandbox Code Playgroud)

\G锚可以在这种情况下是非常有用的,因为它是一种锚,这意味着"在字符串的开头或连续的先例匹配".

但是,模式中没有任何内容检查是否有最后一个数字"].如果需要这样做,则必须向模式添加前瞻:

~(?:\[images ids="|\G(?<!^))([0-9]+)(?=(?:,[0-9]+)*"])(?:,|"])~
Run Code Online (Sandbox Code Playgroud)