需要从文本中找到所有“src”元素


need find from text all "src" elements

>我需要从文本中获取所有"src"元素。"src"可以有"或"。在井中找到的文本,但如果元素有 id,样式...他们也抓住了。我只需要 src 值。

我的代码:

$html = 'text text <img src="img1.png"/> as as <img src=''second.gif'' id ="test" /> as';
preg_match_all('/src=("|'')([^"]*)("|'')/', $html, $htmlSrc);
echo '<pre>';
print_r($htmlSrc);
Array
(
    [0] => Array
        (
            [0] => src="img1.png"
            [1] => src='second.gif' id ="
        )
    [1] => Array
        (
            [0] => "
            [1] => '
        )
    [2] => Array
        (
            [0] => img1.png
            [1] => second.gif' id =
        )
    [3] => Array
        (
            [0] => "
            [1] => "
        )
)

正则表达式是一个坏主意,你最终可能会得到不可维护和不可靠的代码。如果您使用 HTML 解析器,这将既简单又可靠。您可以在此处找到示例:http://simplehtmldom.sourceforge.net/

preg_match_all('/src="|''([^"'']*)"|''/', $html, $htmlSrc);
print_r($htmlSrc[2]);

似乎效果更好。