1

I'd like to extract the img src and using preg_match_all I have this:

$tag = '<img src="path/to/image.png" />';
preg_match_all('/(width|height|src)=("[^"]*")/i',$tag, $img[$tag]);

which returns:

Array
(
[<img src="path/to/image.png" />] => Array
    (
        [0] => Array
            (
                [0] => src="path/to/image.png"
            )

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

        [2] => Array
            (
                [0] => "path/to/image.png"
            )

    )

)

How can I write the regex to return a similar result regardless of double or single quotes used in tag? I can write:

$tag = "<img src='path/to/image.png' />";
preg_match_all('/(width|height|src)=(\'[^\']*\')/i',$tag, $img[$tag]);

Which works, but I'm not familiar enough with regex to write one expression to handle either. I did try:

preg_match_all('/(width|height|src)=((\'[^\']*\')|("[^"]*"))/i',$tag, $img[$tag]);

But this seems to return extra matches in the array which I don't want.

1 Answers1

3

You can use this:

(width|height|src)=("[^"]*"|'[^']*')

I've basically used an alternation to either match "fds" or 'fds'.

Farhad Alizadeh Noori
  • 2,276
  • 17
  • 22
  • Thanks! I know various permutations of this have been asked but mine it not so much about extracting the img as it is about regex syntax for the alternation as you demonstrated. That is exactly what I was going for but still learning regex. – But those new buttons though.. May 23 '14 at 18:05