正则表达式在php中捕获<img/> src

时间:2014-05-23 17:35:09

标签: php regex

我想提取img src并使用preg_match_all我有这个:

$tag = '<img src="path/to/image.png" />';
preg_match_all('/(width|height|src)=("[^"]*")/i',$tag, $img[$tag]);

返回:

Array
(
[<img src="path/to/image.png" />] => Array
    (
        [0] => Array
            (
                [0] => src="path/to/image.png"
            )

        [1] => Array
            (
                [0] => src
            )

        [2] => Array
            (
                [0] => "path/to/image.png"
            )

    )

)

如果标记中使用的双引号或单引号,如何编写正则表达式以返回类似的结果?我可以写:

$tag = "<img src='path/to/image.png' />";
preg_match_all('/(width|height|src)=(\'[^\']*\')/i',$tag, $img[$tag]);

哪个有效,但我对正则表达式不够熟悉,无法编写一个表达式来处理它们。我试过了:

preg_match_all('/(width|height|src)=((\'[^\']*\')|("[^"]*"))/i',$tag, $img[$tag]);

但这似乎返回了我不想要的数组中的额外匹配。

1 个答案:

答案 0 :(得分:3)

您可以使用:

(width|height|src)=("[^"]*"|'[^']*')

我基本上使用了一个替换来匹配&#34; fds&#34;或者&#39; fds&#39;。