I have a problem creating regexpr for capture all IDs from tags imgs. i have a code:
#<span><img (id=\"([^"]*)\").*><\/span>#
Example:
https://regex101.com/r/aN0uO0/3
only capture ID from first tag IMG. Thanks.
I have a problem creating regexpr for capture all IDs from tags imgs. i have a code:
#<span><img (id=\"([^"]*)\").*><\/span>#
Example:
https://regex101.com/r/aN0uO0/3
only capture ID from first tag IMG. Thanks.
Thats because you are not searching globally
, to enable that enter g on the right text field ( after the right / mark ).
If you are using preg_match
in php, use preg_match_all
and it will work.
If you're eager to use a regex at all, you might get along with:
<img[^>]*?id=(['"])(.+?)\1
You'll find the id in the second group ($2
). However, if you have a >
somewhere in an attribute (which is totally valid in HTML
), the regex won't work as expected. In PHP
code this would be:
$regex = '~<img[^>]*?id=([\'"])(.+?)\1~';
$string = 'your_string_here';
preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
See an example on regex101.com.
Hint: It's almost always better to use a parser, e.g. SimpleXML
or DomDocument
.