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

时间:2013-10-02 08:42:11

标签: php preg-match

我需要从文本中获取所有“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] => "
        )

)

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

似乎工作得更好。