user3011784
user3011784

Reputation: 839

foreach loop not working with regex

My file images.html contains multiple lines with the following code:

<linestart><urlstart>http://...image.jpg<urlend><idstart>1<idend><lineend>

I want to parse the file but I can’t figure out my error.

My PHP code:

$pattern = "/<linestart>(.*?)<lineend>/s";
$html = file_get_contents('images.html');

$check = preg_match_all($pattern,$html,$match);

foreach($match[1] as $line)
{ 
$pattern2 = "/<urlstart>(.*?)<urlend>/s";
$check2 = preg_match_all($pattern2,$line,$match_url);

$pattern3 = "/<idstart>(.*?)<idend>/s";
$check3 = preg_match_all($pattern3,$line,$match_id);


echo $match_url." id= ".$match_id."<br>";
}

My result is:

Array id= Array
Array id= Array
Array id= Array
Array id= Array
Array id= Array
Array id= Array

Any ideas why?

Upvotes: 0

Views: 241

Answers (1)

Barmar
Barmar

Reputation: 781848

You can match everything in one pattern:

$pattern = "/<linestart>.*?<urlstart>(.*?)<urlend>.*?<idstart>(.*?)<idend>.*?<lineend>/s";
$html = file_get_contents('images.html');

$check = preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    echo $match[1] . " id=" . $match[2];
}

Upvotes: 1

Related Questions