0
"<img class=\"img-responsive\" src=\"http://localhost/example-local/sites/example/files/styles/thumbnail/public/news-story/gallery-images/Desert.jpg?itok=bqyr-vpK\" width=\"100\" height=\"75\" alt=\"\" /><blockquote class=\"image-field-caption\">\r\n  <p>Desert</p>\n</blockquote>\r\n"

I need to extract only src from this string

I've tried this but its not working for me:

preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i');
Rishi Kulshreshtha
  • 1,748
  • 1
  • 24
  • 35
  • 1
    Don't use regex; use a HTML parser in the language / platform you are working with. Much more reliable. Example for PHP: http://stackoverflow.com/questions/10130858/get-img-src-with-php – Pekka Feb 09 '16 at 10:47

1 Answers1

-1

As pekka said in his comment, PHP has built in tools already for pulling out tags and things of that nature. Your string would be a good example for when to use PHP DOM.

That being said, using regex, I suppose you could just match everything between src=\" and the closing \". Pretty simple to do that:

src=\\"(.*?)\\"

Together, you could do something like this:

<?php

// SET OUR DEFAULT STRING
$string = "<img class=\"img-responsive\" src=\"http://localhost/example-local/sites/example/files/styles/thumbnail/public/news-story/gallery-images/Desert.jpg?itok=bqyr-vpK\" width=\"100\" height=\"75\" alt=\"\" /><blockquote class=\"image-field-caption\">\r\n  <p>Desert</p>\n</blockquote>\r\n";

// USE PREG MATCH TO FIND THE STRING AND SAVE IT IN $matches
preg_match('~src=\\"(.*?)\\"~i', $string, $matches);

// PRINT IT OUT
print $matches[1];

That will give you this:

http://localhost/example-local/sites/example/files/styles/thumbnail/public/news-story/gallery-images/Desert.jpg?itok=bqyr-vpK

Or you could combine the two lines using preg_replace if that tickled your fancy:

print preg_replace('~.*?src=\\"(.*?)\\".*~is', '$1', $string);

This basically just matches everything and overwrites the entire string with whatever it found in the (.*?).

Here is a working demo:

https://ideone.com/OvlaQZ

Quixrick
  • 3,190
  • 1
  • 14
  • 17