PHP从正则表达式中获取数组


PHP get array from regex

我有类似的字符串

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

我想从中删除[images ids="10,11,20,30,40"]部分,并将ID部分作为php array(10,11,20,30,40)

使用regex可能吗?

您可以使用这个:

$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);

CCD_ 3锚在这种情况下可能非常有用;在字符串的开头或与前一个匹配"相邻"处 。

但是,模式中没有任何内容检查是否有最后一个后面跟有"]的数字。如果你需要这样做,你必须在模式中添加一个前瞻性:

~(?:'[images ids="|'G(?!^))([0-9]+)(?=(?:,[0-9]+)*"])(?:,|"])~

假设这是内容的结构,并且不会变得更复杂,那么:

preg_match_all('/('d+)/', $content, $matches);
print_r($matches[0]);

如果它更复杂,则需要添加更多内容来缩小范围。