Miguelos
Miguelos

Reputation: 302

Get all matches using regexp preg_match() function in PHP

I'm using preg_match to search for img elements in an xml with a specific src or href pattern. Examples: < img src= "level1/level2/2837", < img href ='level1/level2/54322'.

preg_match('/< *\/? *' // Begining of xml element
  . 'img' // "img" atribute
  . '[^>]*' // Any character except >
  . '(?:src|href) *= *' // src or href attribute with possible spaces between =
  . '(?:"|\')level1\/level2\/(\d+)(?:"|\')/', // "level1/level2/2837"
  $subject, $matches);

It works but only returns the first match.

For example if subject has this content:

$subject = "< img  src= 'level1/level2/2837'/> <p>something</p> < img  href ='level1/level2/54322'";

The result I get is:

$matches => Array 
    ( 
        [0] => '< img  src= "level1/level2/2837"' 
        [1] => '2837' 
    ) 

How can I get all the matches in $matches array?

I've already used simplexml_load_string to achieve this but would like to understand how regular expressions work with preg_match.

Upvotes: 1

Views: 461

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

You need to turn ["|'] to (?:"|') . This ['|"] would match ' or | or ". And also you need to use preg_match_all in-order to do a global match.

preg_match_all('/< *\/? *'
  . 'img'
  . '[^>]*'
  . '(?:src|href) *= *'
  . '(?:"|\')level1\/level2\/(\d+)(?:"|\')/', 
  $subject, $matches);

Upvotes: 2

Miguelos
Miguelos

Reputation: 302

Use preg_match_all instead of preg_match.

Upvotes: 3

Related Questions