Saturday, June 16, 2018

Regex to capture src in php




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



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


which returns:




Array
(
[] => 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 = "";
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.


Answer



You can use this:




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


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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...