preg_match - 为什么两个相同的项目在比赛中


preg_match - Why two identical items in matches

$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属性中提取 URL。我$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] 有两个相同的项目?我怎样才能避免这种情况?

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

只需删除$map,在preg_match('/src'='"((.*?))'"/i',$map, $matches);处使用 $str 即可。停止使用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
)