I made this regex to get all attributes in tag "img".
/<img\s+(?:([a-z_-]+)\s*=\s*"(.*?)"\s*)*\s*\/>/g
But, It just take only one attribute which is last.
How can I get all attributes with regex?
Test String:
<img src="abc.png" alt="abc" />
<img alt="def" src="def.png" />
<img src="abc.png" alt="abc" style="border:none" />
<img alt="def" src="def.png" style="border:none" />
Result: (with http://www.regex101.com)
MATCH 1
1. [19-22] `alt`
2. [24-27] `abc`
MATCH 2
1. [47-50] `src`
2. [52-59] `def.png`
MATCH 3
1. [93-98] `style`
2. [100-111] `border:none`
MATCH 4
1. [145-150] `style`
2. [152-163] `border:none`
I suggest you to use \G
anchor in-order to do a continuous string match.
(?:<img|(?<!^)\G)\h*([\w-]+)="([^"]*)"(?=.*?\/>)
Get the attribute from group index 1 and get the value from group index 2.
DEMO
$string = <<<EOT
<img src="abc.png" alt="abc" />
<img alt="def" src="def.png" />
<img src="abc.png" alt="abc" style="border:none" />
<img alt="def" src="def.png" style="border:none" />
EOT;
preg_match_all('~(?:<img|(?<!^)\G)\h*(\w+)="([^"]+)"(?=.*?\/>)~', $string, $match);
print_r($match[1]);
print_r($match[2]);
Output:
Array
(
[0] => src
[1] => alt
[2] => alt
[3] => src
[4] => src
[5] => alt
[6] => style
[7] => alt
[8] => src
[9] => style
)
Array
(
[0] => abc.png
[1] => abc
[2] => def
[3] => def.png
[4] => abc.png
[5] => abc
[6] => border:none
[7] => def
[8] => def.png
[9] => border:none
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With