how to use multiple preg_match with one foreach loop
I have multiple preg match expressions, and I'm trying 开发者_JAVA百科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
Try this,
$title = array();
$thumb = array();
$string = '';
preg_match_all("/\<div class=\"merchant_info\">\s*(\<div.*?\<\/div>\s*)?(.*?)\<\/div\>/is", $res[0], $matches );
foreach($matches[0] as $titles){
$title[] = "<div class='titles' >".$titles."</div>";
}
preg_match_all("/\<a class=\"thumb\"(.*?)\<\/a\>/is", $res[0], $matches);
foreach($matches[0] as $thumbs){
$thumb[] = "<div class='thumbs' >".$thumbs."</div>";
}
for($i = 0; $i < count($title); $i++){
$string .= $title[$i] . $thumb[$i];
}
echo $string;
Should the list of matches correlate, you could simple combine it this way:
preg_match_all("/\<div class=\"merchant_info\">\s*(\<div.*?\<\/div>\s*)?(.*?)\<\/div\>/is", $res[0], $matches );
preg_match_all("/\<a class=\"thumb\"(.*?)\<\/a\>/is", $res[0], $second);
foreach($matches[0] as $i => $titles)
{
echo "<div class='titles' >".$titles."</div>";
echo "<div class='thumbs' >".$second[$i]."</div>";
}
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.
preg_match_all("/\<div class=\"merchant_info\">\s*(\<div.*?\<\/div>\s*)?(.*?)\<\/div\>/is", $res[0], $matches[] );
preg_match_all("/\<a class=\"thumb\"(.*?)\<\/a\>/is", $res[0], $matches[]);
foreach($matches[0][0] as $i => $titles)
{
echo "<div class='titles' >".$titles."</div>";
echo "<div class='thumbs' >". $matches[1][0][$i]."</div>";
}
精彩评论