如何在一个 foreach 循环中使用多个 preg_match
我有多个 preg 匹配表达式,并且我尝试使用每个表达式来输出不同的内容。我知道如何使用 foreach 一次输出一个。但我如何回显或将它们设置为变量?
preg_match_all("/\<div class=\"merchant_info\">\s*(\<div.*?\<\/div>\s*)?(.*?)\<\/div\>/is", $res[0], $matches );
foreach($matches[0] as $titles)
{
echo "<div class='titles' >".$titles."</div>";
}
preg_match_all("/\<a class=\"thumb\"(.*?)\<\/a\>/is", $res[0], $matches);
foreach($matches[0] as $thumbs)
{
echo "<div class='thumbs' >".$thumbs."</div>";
}
我希望能够将标题和拇指一起呼应。或者我是否可以将它们设置为变量然后将其输出到其他地方?
谢谢
I have multiple preg match expressions, and I'm trying to use each to output something different. I know how to use foreach to output one at a time. but how do I echo or set them a variable?
preg_match_all("/\<div class=\"merchant_info\">\s*(\<div.*?\<\/div>\s*)?(.*?)\<\/div\>/is", $res[0], $matches );
foreach($matches[0] as $titles)
{
echo "<div class='titles' >".$titles."</div>";
}
preg_match_all("/\<a class=\"thumb\"(.*?)\<\/a\>/is", $res[0], $matches);
foreach($matches[0] as $thumbs)
{
echo "<div class='thumbs' >".$thumbs."</div>";
}
I want to be able to echo the titles and thumbs together. or if i can set them as a variable and then output it somewhere else?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个,
Try this,
如果匹配列表相互关联,您可以简单地以这种方式组合它:
注意第二个
preg_match_all
如何使用结果变量$second
。$i
是第一个$matches
数组的数字索引,但按原样用于 $第二个数组。顺便提一句。我完全赞成使用正则表达式。但考虑到匹配的复杂性,这可能是您的代码可能受益于使用 HTML 解析器的情况之一。 phpQuery 或 QueryPath 使提取内容变得更加简单并确保标题确实属于到缩略图。
Should the list of matches correlate, you could simple combine it this way:
Note how the second
preg_match_all
uses the result variable$second
. The$i
is the numeric index of the first$matches
array, but is used as-is for the $second.Btw. I'm all for using regular expressions. But seeing the complexity of the match this might be one of the cases where your code might benefit from using a HTML parser instead. phpQuery or QueryPath make it much simpler to extract the contents and ensure that the titles really belong to the thumbnails.