0

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?

8
  • 2
    What are you expecting? $match_url and $match_id are arrays of all the matches. You need to loop over them, like you do with $match. Commented Feb 15, 2014 at 0:09
  • Can you have more than one <urlstart> or <idstart> in each <linestart> block? If not, you could use preg_match instead of preg_match_all. Commented Feb 15, 2014 at 0:10
  • each line only has 1 <urlstart>. I tried preg_match instead of preg_match_all.. same result. the result should be URL and the the ID (1 result per line) Commented Feb 15, 2014 at 0:13
  • You still need to subscript the match to get the capture group. Commented Feb 15, 2014 at 0:13
  • Barnmar... I don't understand what that means... "subscript to capture the group" ? Commented Feb 15, 2014 at 0:16

1 Answer 1

1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.