在从数据库中获取数据后,我正在编写代码,从变量$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);结果仍然一样。我试图在谷歌上找到答案,但我找不到解决方案的答案。
不幸的是,我无法找到解决方案,因为我不知道如何使用preg_match_all获取href标记来显示元素并存储在数组中。
我发现的问题与变量$matches有关。
您能给我举个例子吗?我可以使用preg_match_all来获取href标记,这样我就可以存储数组中的元素了?
谢谢。
发布于 2018-12-27 21:18:51
如全文档中所写
$out包含匹配完整模式的字符串数组,$out 1包含由标记包围的字符串数组。
这样你就可以像下面这样做
foreach($matches[0] as $url)
{
echo $url;
}发布于 2018-12-27 21:14:52
试试这个:
foreach($matches[0] as $url)
{
echo $url;
}发布于 2018-12-27 21:17:49
嗨,
据我正确的理解,您的问题是,您收到了一个到多个嵌套数组和结果,您不能读取您的URL,也是数组?
您可以使用的解决方案之一是消除不必要的嵌套数组。您可以通过使用PHP函数array_shift()来做到这一点。
来自php.net手册
array_shift()将数组的第一个值移开并返回.
因此,诀窍是返回的值将是您的数组,您可以通过它循环数据。
你的案例中有一些样本:
//from the moment when you use preg_match_all and have matches
preg_match_all($regex, $message, $matches);
$urls = array_shift($matches);
foreach($urls as $url) {
//do something with URL
}当然,您可以不同地使用array_shift(),这只是一个简单的示例;)
干杯!
https://stackoverflow.com/questions/53950821
复制相似问题