返回匹配数组的PHP正则表达式(preg_match vs preg_match_all)

时间:2018-03-30 11:37:29

标签: php arrays regex

我正在尝试获取我的正则表达式的所有成功匹配的数组,在这种情况下是所有数据URI的数组,以便遍历数组并将每个数据URI转换为文件。

<?php
$string = '<img src="data:image/png;base64,FAKEIMAGE0XXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 0" /><img src="data:image/png;base64,FAKEIMAGE1XXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 1" /><img src="data:image/png;base64,FAKEIMAGE2XXXXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 2" /><img src="data:image/png;base64,FAKEIMAGE3XXXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 3" />';
$pattern = '@src="([^"]+)"@';
echo preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
var_dump($matches);

我想得到如下结果:

 Array(4) { [0]=> string(60) "data:image/png;base64,FAKEIMAGE0XXXXXAKJDBFLASDGFSDGAFJLSD==" [1]=> string(60) "data:image/png;base64,FAKEIMAGE1XXXXXAKJDBFLASDGFSDGAFJLSD==" [2]=> string(62) "data:image/png;base64,FAKEIMAGE2XXXXXXXAKJDBFLASDGFSDGAFJLSD==" [3]=> string(61) "data:image/png;base64,FAKEIMAGE3XXXXXXAKJDBFLASDGFSDGAFJLSD==" }

2 个答案:

答案 0 :(得分:3)

您可以使用DOMDocument并使用getElementsByTagName查找图片,而不是使用regex to parse html

$string = '<img src="data:image/png;base64,FAKEIMAGE0XXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 0" /><img src="data:image/png;base64,FAKEIMAGE1XXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 1" /><img src="data:image/png;base64,FAKEIMAGE2XXXXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 2" /><img src="data:image/png;base64,FAKEIMAGE3XXXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 3" />';
$dom = new DOMDocument();
$dom->loadHTML($string);
$srcs = [];
foreach ($dom->getElementsByTagName('img') as $img) {
    $srcs[] = $img->getAttribute("src");
}
var_dump($srcs);

Demo

答案 1 :(得分:0)

使用以下代码重写代码解决了获取分配给$matches的结果数组的问题:

$string = '<img src="data:image/png;base64,FAKEIMAGE0XXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 0" /><img src="data:image/png;base64,FAKEIMAGE1XXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 1" /><img src="data:image/png;base64,FAKEIMAGE2XXXXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 2" /><img src="data:image/png;base64,FAKEIMAGE3XXXXXXAKJDBFLASDGFSDGAFJLSD==" alt="Fake img 3" />';
$pattern = '@src="([^"]+)"@';
echo preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
var_dump($matches[1]);