-1

is this a limitation on any regex result? What I need is to get all the occurrence in a single line, but preg_match_all return the first and end of the expression. Is there any other way to get all the occurrence on the line?

$re = "/(media|images)(.*)(.jpg|.jpeg|.png)/";
$str = 'images/test/test-1.png" alt="test-1" /></a><a href="/test-2" title="test 2"><img src="/images/test/test2.png" alt="test2" /></a>               <a href="/test-3" title="Cruises in Croatia"><img src="/images/EET/test-3.png';
preg_match_all($re,$str,$matches );
print_r($matches);

This is what I get.

Array
(
    [0] => Array
        (
            [0] => images/test/test-1.png" alt="test-1" /></a><a href="/test-2" title="test 2"><img src="/images/test/test2.png" alt="test2" /></a>               <a href="/test-3" title="Cruises in Croatia"><img src="/images/EET/test-3.png
        )

    [1] => Array
        (
            [0] => images
        )

    [2] => Array
        (
            [0] => /test/test-1.png" alt="test-1" /></a><a href="/test-2" title="test 2"><img src="/images/test/test2.png" alt="test2" /></a>               <a href="/test-3" title="Cruises in Croatia"><img src="/images/EET/test-3
        )

    [3] => Array
        (
            [0] => .png
        )

)

Forbidden
  • 109
  • 2
  • 10
  • What do you mean by `get all the occurrence in a single line` ? What you get is the expected behaviour, it will give you an array with all matches, matches meaning here every match for every capture group – empiric Nov 08 '19 at 07:18
  • Are you trying to get all image paths? – Ogreucha Nov 08 '19 at 07:19

1 Answers1

1

You need to make your regex non-greedy by adding a ? on your quantifier (.*).

The regex should something like this:

(media|images)(.*?)(.jpg|.jpeg|.png)

Example code:

$re = "/(media|images)(.*?)(.jpg|.jpeg|.png)/";
$str = 'images/test/test-1.png" alt="test-1" /></a><a href="/test-2" title="test 2"><img src="/images/test/test2.png" alt="test2" /></a>               <a href="/test-3" title="Cruises in Croatia"><img src="/images/EET/test-3.png';
preg_match_all($re,$str,$matches );
print_r($matches);

https://3v4l.org/8Haqm

Ogreucha
  • 633
  • 1
  • 5
  • 24
  • Wow, thanks alot, this is exactly what I needed, Sadly I could not vote, my reputation is not yet capable :( – Forbidden Nov 08 '19 at 08:21