1

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

j_freyre
  • 4,565
  • 2
  • 28
  • 45
hellomello
  • 7,669
  • 35
  • 133
  • 276

3 Answers3

2

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.

Community
  • 1
  • 1
mario
  • 141,508
  • 20
  • 234
  • 284
  • I'll look into the html parser. I couldn't get this one to work. I think the other solution worked better because I now know how to get multiple arrays if I have to do more than 2. – hellomello Mar 16 '11 at 20:00
2

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;
kushalbhaktajoshi
  • 4,582
  • 3
  • 21
  • 37
1
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>";
}
Angelin Nadar
  • 8,556
  • 9
  • 41
  • 52