Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all of attributes with regex?

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`
like image 980
WebEngine Avatar asked Jan 10 '23 01:01

WebEngine


1 Answers

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
)
like image 141
Avinash Raj Avatar answered Jan 24 '23 14:01

Avinash Raj