Reputation: 386
I know that this question has been posted a lot of times and I read through all the previous questions. I could not find a way to make this work.
I need to extract the src url of an img tag with a particular id. Input format is -
<img class"image" id="prdImage" width="277" height="400" alt="someimage" src="http://url/image.jpg"/>
src attribute is always the last, class is always the first. Also, this code will be in a large HTML document. I only gave the relevant part.
What I have till now-
/<img class="image" id="prdImage".+?src="(.+?)".+?\/>/i
This is working fine except that it is returning the entire img tag instead of only the src attribute;
Note: I know that I should use a DOM parser for such cases. But for this project, I can only use regular expressions.
Upvotes: 0
Views: 1959
Reputation: 386
I figured out the answer myself. Here is the expression
/<img class="image" id="prdImage"(.*?)src="(.*?)"\/>/i
This will return an array with the url in the second position.
I am accepting this answer since I figured it out myself. If anybody else has a better solution, I will accept their answer.
Upvotes: 0
Reputation: 114
Try this
(?<=<img.*?src=")(.*?)(?="/>)
That regex will return
http://url/image.jpg
from your input string
<img class"image" id="prdImage" width="277" height="400" alt="someimage" src="http://url/image.jpg"/>
Upvotes: 1