1

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.

  • Hover over that question mark to the right of the regex input; – Rizier123 Mar 22 '16 at 16:17
  • 2
    You'll probably be better off using a parser unless the format is consistent. If other attributes are present between `img` and `id` the `id` will not be found with this regex. – chris85 Mar 22 '16 at 16:24
  • Looks like you're attempting to use regex on HTML. [Obligatory warning.](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – amphetamachine Mar 22 '16 at 20:16

2 Answers2

0

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.

ogres
  • 3,660
  • 1
  • 17
  • 16
0

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.

Jan
  • 42,290
  • 8
  • 54
  • 79