user1610115
user1610115

Reputation: 39

RegEx for preg_match_all not working

This is my string ($string):

    swatch: 'http://abc.com/aa.jpg',
    zoom:[
      'http://abc.com/bb.jpg'
    ],
    large:[

      'http://abc.com/cc.jpg'
    ],

I use the following pattern in my PHP file and want to match http://abc.com/bb.jpg:

preg_match_all('/(?<=zoom:\[\s{15}\').*(?=\')/', $string, $image);

But nothing is returned. What should I do?

Upvotes: 2

Views: 158

Answers (1)

HamZa
HamZa

Reputation: 14921

To make it simpler, we won't use look around and although I said that we need the s modifier, I was wrong it's only used to match new lines with dots . which we won't be using here, so \s matches a new line:

$string = <<<JSO
        swatch: 'http://abc.com/aa.jpg',
        zoom:[
          'http://abc.com/bb.jpg'
        ],
        large:[

          'http://abc.com/cc.jpg'
        ],
JSO;
preg_match_all('/zoom:\[\s*\'(?<img>[^\']*)\'\s*\]/', $string, $m);
print_r($m['img']);

Output:

Array
(
    [0] => http://abc.com/bb.jpg
)

Explanation:

/ # Starting delimiter
    zoom:\[ # Matches zoom:[
    \s* # Matches spaces, newlines, tabs 0 or more times
    \'  # Matches '
    (?<img>[^\']*) # named group, matches everything until ' found
    \'  # Matches '
    \s* # Matches spaces, newlines, tabs 0 or more times
    \]  # Matches ]
/ # Ending delimiter

Upvotes: 1

Related Questions