Naveen Gamage
Naveen Gamage

Reputation: 1884

how to combine two grabbed variables using preg_match_all?

I use preg_match_all to grab urls and titles from another page and grabbing is ok but i cant get them in to one using foreach! or is there another way instead of foreach?

//gets URLs of href='xxxx'   
 preg_match_all('/a href="([^"]+)" class=l.+?>.+?<\/a>/',$sear,$results);

//gets titles of >xxxx</a>   
    preg_match_all('/a href=".+?" class=l.+?>([^"]+)<\/a>/',$sear,$t);

Below code Displays grabbed URLs

foreach ($results[1] as $url)
{
echo "<a href='$url'>$u</a> <br>";

$i++;
}

Below code Displays grabbed titles

   foreach ($t[1] as $title)
   { 
   echo $title; 
   $i++;
   }

but i dont know how to display them(url & title) in one foreach so i can make it like

<a href='URL'>Title</a> 

Upvotes: 0

Views: 250

Answers (1)

nickb
nickb

Reputation: 59699

Combine the two regular expressions to capture both items in one shot:

preg_match_all('/<a href="([^"]+)" class=l.+?>([^<]+)<\/a>/',$sear, $results);
var_dump( $results);

Now you have both the URL and the title in capturing groups 1 and 2.

An improvement on this regex would be to use a positive lookahead to match the closing </a>, but for simplicity your current solution should be fine.

Edit: I originally left it up to the OP to figure out how to grab the correct output from the results. However, here is a working example.

for( $i = 0; $i < count( $results[1]); $i++)
    echo 'URL: ' . $results[1][$i] . ', Title: ' . $results[2][$i];

Upvotes: 1

Related Questions