-1

I have xml file:

<set>
<item>
    <id>1</id>
    <title>title1</title>
</item>
<item>
    <id>2</id>
    <title>title2</title>
</item>
<item>
    <id>3</id>
    <title>title3</title>
    <img>img3</img>
</item> 
</set>

And i need to parse only elements with "img" and get "id -> img". I use regular expression

preg_match_all('~<item>.*?<id>(.*?)</id>.*?<img>(.*?)</img>.*?</item>~si', $source, $result);

and i get "id" = '1' and "img" = 'img3', but i need "id" = '3' and "img" = 'img3'.

Please help me with my regular expression.

Ahosan Karim Asik
  • 3,219
  • 1
  • 18
  • 27
Kirill Che
  • 39
  • 5

1 Answers1

0

Don't parse html file with regex. If you wanna solution use regex then you could try the below.

'~<item>.*?<id>((?:(?!<id>).)*?)</id>(?:(?!<item>).)*<img>(.*?)</img>.*?</item>~si'

DEMO

(?:(?!<id>).)*? Non-greedy match of any character but not of <id>, zero or more times.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274