3

I have the following data in MySQL.

<p><img src="../../../../assets/images/frontpage/image1.png" 
alt="" width="790" height="356" /></p>

Now I want to get image2.png with PHP or regex. The extension can be gif or jpg. And a length of image name can be any length.

halfer
  • 19,824
  • 17
  • 99
  • 186
shin
  • 31,901
  • 69
  • 184
  • 271
  • Worth noting is whether you want to be able to match this on multiple img-tags or just one. – rzetterberg Jul 03 '11 at 17:04
  • 1
    http://stackoverflow.com/questions/3650125/how-to-parse-html-with-php – derobert Jul 03 '11 at 17:08
  • possible duplicate of [Regular expression in PHP to return array with all images from html, eg: all src="images/header.jpg" instances](http://stackoverflow.com/questions/5721025/regular-expression-in-php-to-return-array-with-all-images-from-html-eg-all-src) – mario Jul 03 '11 at 17:08
  • And, of course, http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – derobert Jul 03 '11 at 17:11
  • 1
    "I want to get image2.png with PHP or regex" doesn't really tell us what you're trying to do. "Get" image2.png how? Your example has "image1.png". – Lightness Races in Orbit Jul 03 '11 at 20:44

4 Answers4

3

This would match a path in an img tag and capture the file in the first interior capturing group.

<?php
if (preg_match('%<img\s.*?src=".*?/?([^/]+?(\.gif|\.png|\.jpg))"%s', $subject, $regs)) {
    $image = $regs[1];
} else {
    $image = "";
}
?>
Justin Aquadro
  • 2,280
  • 3
  • 21
  • 31
0

This code should do what you need:

<?php
$regex = '@src[ ]*=[ ]*"[a-z/.]*/(.*?\.(?:png|gif|jpg))@i"';
$match = array();
if (preg_match($regex, $html, $match)) {
    $imglocation = $match[1];
} else {
    die('Failed to find image name.');
}
EdoDodo
  • 8,220
  • 3
  • 24
  • 30
  • $html = '

    '; $regex = 'src[ ]*=[ ]*"[a-zA-Z/.]*/(.*?\.(?:png|gif|jpg))"'; $match = array(); if (preg_match($regex, $html, $match)) { $imglocation = $match[1]; } else { die('Failed to find image name.'); }. This gives the following error. Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in C:\xampp\htdocs\test\test1.php on line 19 Failed to find image name.
    – shin Jul 03 '11 at 17:02
  • 1
    Whoops, I forgot to include a delimiter. Added now. – EdoDodo Jul 03 '11 at 17:05
0

Try this:

$str = '<p><img src="../../../../assets/images/frontpage/image1.png" 
alt="" width="790" height="356" /></p>'; 
$imageType = end(explode(".")); 
The Mask
  • 17,007
  • 37
  • 111
  • 185
-2

Use this expression: var expr=/[a-z]+\.(gif|jpg)$/;

Jon
  • 2,932
  • 2
  • 23
  • 30
Ankur
  • 3,584
  • 1
  • 24
  • 32