How can I extract image src
from an text that only contains img
tag?
And by the way src
is double quote sometimes and in single quote sometimes.
Asked
Active
Viewed 3,830 times
1

Muhammad Hassaan
- 7,296
- 6
- 30
- 50

Aref Anafgeh
- 512
- 1
- 6
- 20
-
no attempts yet...i was thinking to regex – Aref Anafgeh Aug 15 '15 at 06:40
-
Why you choose regex, what's wrong with dom parser? – Avinash Raj Aug 15 '15 at 06:48
-
i only have string that contains some description of data that may have a img element – Aref Anafgeh Aug 15 '15 at 06:56
-
possible duplicate of [Regex & PHP - isolate src attribute from img tag](http://stackoverflow.com/questions/2120779/regex-php-isolate-src-attribute-from-img-tag) – Jonny 5 Aug 15 '15 at 07:42
-
For both quote styles try something [like this](https://regex101.com/r/wV0uS7/2): `\ssrc\s*=\s*['"]\s*\K[^'"\s]+` – Jonny 5 Aug 18 '15 at 16:00
2 Answers
6
I would not recommend using regex to parse html. Instead you can use php's DOMDocument()
class, which should still work even if the rest of the string isn't really html:
$html = 'Lorem ipsum<img src="test.png">dolor sit amet&[H*()';
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
$imgs = $dom->getElementsByTagName('img');
foreach($imgs as $img) {
$src = $img->getAttribute('src');
echo $src;
}
Depending on your php version you may also want to use:
$dom->loadHTML($a, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

But those new buttons though..
- 21,377
- 10
- 81
- 108
1
Try
$image = '<img class="foo bar test" title="test image" src=\'http://example.com/img/image.jpg\' alt="test image" width="100" height="100" />';
$array = array();
preg_match( "/src='([^\"]*)'/i", $image, $array ) ;
print_r( $array[1] ) ;

Muhammad Hassaan
- 7,296
- 6
- 30
- 50
-
1this works fine but the problem is that src attr is sometimes in single quote and in that case your code does not work – Aref Anafgeh Aug 15 '15 at 06:49
-
If my answer works fine for you then why you did not accept my answer? – Muhammad Hassaan Aug 15 '15 at 09:31
-
well your answer works but according to my research using REGEX for this kind of problems is not best Way.using DOMDocuments is more reliable – Aref Anafgeh Aug 15 '15 at 09:48
-
@ArefAnafgeh You ask about `regex` so I give you answer according to `regex`. You did mention in your question to get best way of exporting images from web. Btw `regex` is more speedy way. – Muhammad Hassaan Aug 15 '15 at 10:22
-
1