preg_match - 为什么匹配中有两个相同的项目

时间:2016-04-26 12:22:11

标签: php preg-match

$str = '<iframe src="https://www.google.com/maps/place/the-big-junky-map-url-with-lat-lon-etc-etc" width="100%" height="350" frameborder="0" style="border:0;" allowfullscreen></iframe>';
$matches  = array();
preg_match('/src\=\"((.*?))\"/i',$map, $matches);
echo '<pre>';print_r($matches);die();

我想从src属性中提取网址。我在$matches中得到了关注。

Array
(
    [0] => src="https://www.google.com/maps/place/the-big-junky-map-url-with-lat-lon-etc-etc"
    [1] => https://www.google.com/maps/place/the-big-junky-map-url-with-lat-lon-etc-etc
    [2] => https://www.google.com/maps/place/the-big-junky-map-url-with-lat-lon-etc-etc
)

我得到了我需要的东西,但为什么在[1]和[2]有两个相同的项目?我怎么能避免这个?

2 个答案:

答案 0 :(得分:1)

删除.*?周围的额外括号。他们定义了一个捕获组,现在你在一个捕获组中有一个捕获组,因此有两个相同的结果。

答案 1 :(得分:0)

只需移除$map,在$str使用preg_match('/src\=\"((.*?))\"/i',$map, $matches);即可。停止使用结果的double capturing group

试试这个

$str = '<iframe src="https://www.google.com/maps/place/the-big-junky-map-url-with-lat-lon-etc-etc" width="100%" height="350" frameborder="0" style="border:0;" allowfullscreen></iframe>';
$matches  = array();
preg_match('/src\=\"(.*?)\"/i',$str, $matches);

echo '<pre>';
print_r($matches);

<强>结果

Array
(
    [0] => src="https://www.google.com/maps/place/the-big-junky-map-url-with-lat-lon-etc-etc"
    [1] => https://www.google.com/maps/place/the-big-junky-map-url-with-lat-lon-etc-etc
)