Menü schliessen
Created: May 1st 2014
Last updated: May 1st 2020
Categories: Common Web Development
Author: Marcus Fleuti

Fetch img tags with all attributes from a PHP string using a regex pattern and capture groups

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

How to fetch all <img> tags from a PHP string using regex and capture groups

/* the regex pattern will look for an image tag and create individual capture groups
 * for 'class'(1), 'src'(2), 'alt'(3), 'width'(4) and 'height'(5). The numbers within the brackets stand for the capture group number
 * respectively the key within the PHP array. The array key 0 will contain the whole <img> tag with all attributes (the full img link)
 * First we define the pattern, then we use the PHP function 'preg_match_all' fo find all occurences within the given string. */
$pattern = '/<img\s*(?:class\s*\=\s*[\'\"](.*?)[\'\"].*?\s*|src\s*\=\s*[\'\"](.*?)[\'\"].*?\s*|alt\s*\=\s*[\'\"](.*?)[\'\"].*?\s*|width\s*\=\s*[\'\"](.*?)[\'\"].*?\s*|height\s*\=\s*[\'\"](.*?)[\'\"].*?\s*)+.*?>/si';
preg_match_all($pattern, $item->fulltext, $matches);
/* as an example we iterate through the list of image sources (src) and build up a custom image link. We needed this in order to create
 * proper a links from images in order to be able to use fancybox for opening images that were added in an article in Joomla */
foreach ($matches[2] as $key => $value) {
    ?>
        <a style="display:none;" class="blog-gallery-image fancyboxpopup" alt="<?=$matches[3][$key]?>" rel="fancygroup<?=$blogitemcount?>" href="<?=$value?>">link</a>
    <?
}