我有字符串
$content = "Some content some content [images ids="10,11,20,30,40"] Some content";
我想从中删除[images ids="10,11,20,30,40"]
部分并获取id作为phparray(10,11,20,30,40)
正则表达式有可能吗?
你可以用这个:
$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);
该\G
锚可以在这种情况下是非常有用的,因为它是一种锚,这意味着"在字符串的开头或连续的先例匹配".
但是,模式中没有任何内容检查是否有最后一个数字"]
.如果需要这样做,则必须向模式添加前瞻:
~(?:\[images ids="|\G(?<!^))([0-9]+)(?=(?:,[0-9]+)*"])(?:,|"])~