从preg_match_all中提取所有网址

时间:2018-12-27 20:59:19

标签: php arrays

当我从数据库中获取数据之后,我正在研究从变量$message获取href网址的代码。使用preg_match_all从变量获取href标签时遇到问题,因为它将在输出中两次显示数组。

以下是输出:

Array ( [0] => Array ( [0] => https://example.com/s-6?sub=myuserid [1] => https://example.com/s-6?sub=myuserid 
[2] => https://example.com/s-6?sub=myuserid [3] => https://www.example2.com/1340253724 [4] => https://example.com/s-6?sub=myuserid ) )

应该是:

Array ( [0] => https://example.com/s-6?sub=myuserid [1] => https://example.com/s-6?sub=myuserid 
[2] => https://example.com/s-6?sub=myuserid [3] => https://www.example2.com/1340253724 [4] => https://example.com/s-6?sub=myuserid ) )

这是一个最小的示例:

<?php

$message = '<a href="https://example.com/s-6?sub=myuserid">Click Here!</a>
<a href="https://example.com/s-6?sub=myuserid">Watch The Video Here!</a>
<a href="https://example.com/s-6?sub=myuserid">HERE</a>
<a href="https://www.example2.com/1340253724">Example2.com/1340253724</a>
<a href="https://example.com/s-6?sub=myuserid">Here</a>';

//find the href urls from the variable       
$regex = '/https?\:\/\/[^\" ]+/i';
preg_match_all($regex, $message, $matches);
print_r(matches);
?>

我尝试使用这种不同的方式:

foreach($matches as $url) 
{
    echo $url;
}

我也尝试过这个:

foreach($matches as $url) 
{
    $urls_array[] = $url;
}

print_r($urls_array);

结果仍然相同。我试图在Google上找到答案,但是找不到解决方案的答案。

不幸的是,我无法找到解决方案,因为我不知道如何使用preg_match_all来获取href标签以显示元素并存储在数组中。

我发现的问题与名为$matches的变量有关。

能否请您举一个示例,说明如何使用preg_match_all来获取href标签,以便可以将元素存储在数组中?

谢谢。

3 个答案:

答案 0 :(得分:1)

尝试一下:

foreach($matches[0] as $url) 
{
    echo $url;
}

答案 1 :(得分:1)

嗨,

据我正确理解,您的问题是您收到了一对多嵌套的结果数组,而您无法读取也作为数组的URL?

您可以使用的解决方案之一是摆脱不必要的嵌套数组。您可以使用PHP Array函数use std::cell::RefCell; use std::rc::Rc; let sink_infos: Rc<RefCell<Vec<StreamInfo>>> = Rc::new(RefCell::new(Vec::new())); let sink_infos2 = sink_infos.clone(); // Create a new Rc which points to the same data. let op = introspector.get_sink_input_info_list(move |result| match result { pulse::callbacks::ListResult::Item(info) => sink_infos2.borrow_mut().push(info.into()), pulse::callbacks::ListResult::End => {}, pulse::callbacks::ListResult::Error => panic!("Error getting sink input info"), }); 来完成此操作。

来自php.net manual

  

array_shift()将数组的第一个值移开并返回[...]

因此,诀窍在于,返回值将是您的数组,其中包含可以循环的数据。


有关您的案例的一些示例:

array_shift()

当然,您可以不同地使用array_shift(),那只是一个简单的示例;)


干杯!

答案 2 :(得分:1)

如文档preg_match_all

中所述
  

$ out [0]包含与完整模式匹配的字符串数组,并且   $ out [1]包含由标签括起来的字符串数组。

所以您可以喜欢

foreach($matches[0] as $url) 
{
    echo $url;
}
相关问题