Santanu
Santanu

Reputation: 8064

Regular expression to find "src" attribute of HTML "img" element in PHP

I have a string, inside of that I have an image:

"<p><img src="http://yahoo.com/testfolder/userdata/editoruploadimages/confused man.jpg" /></p>"

I could not fetch the image URL with my regular expression. My code is:

preg_match_all("/src=([^\\s]+)/", $questArr_str, $images);

This code stops its execution when it encounters the space in the image name. It only returns "http://yahoo.com/testfolder/userdata/editoruploadimages/confused

The returned string should be: "http://yahoo.com/testfolder/userdata/editoruploadimages/confused man.jpg"

Upvotes: 5

Views: 24368

Answers (4)

iKev61
iKev61

Reputation: 194

Here is an easy way to match <img /> tag src attribute and or it content in html/PHP with regular expression.

Sample:

<img class="img img-responsive" title="publisher.PNG" src="media/projectx/agent/author/post/2/image/publisher.PNG" alt="" width="80%" />

To match just src attribute content use

preg_match("%(?<=src=\")([^\"])+(png|jpg|gif)%i",$input,$result)

$result[0] will output media/projectx/agent/author/post/2/image/publisher.PNG

To match `src' attribute and it content use

preg_match("%src=\"([^\"])+(png|jpg|gif)\"%i",$input,$result)

$result[0] will output src="media/projectx/agent/author/post/2/image/publisher.PNG"

Upvotes: 1

Santanu
Santanu

Reputation: 8064

Thank every one for helping me out.

I found my solution by using:

pattern = "/src=([^\\\"]+)/"

Upvotes: 1

Beat
Beat

Reputation: 1380

I'd catch everything inside the quotes:

preg_match_all('/src="([^"]+)"/', $questArr_str, $images);

Upvotes: 13

Adrian Thompson Phillips
Adrian Thompson Phillips

Reputation: 7141

The parts that reads ([^\s]+) means select anything that isn't a space.

Maybe try something like:

/src="([^"]+)"/

Which is select anything that isn't a double quote.

Upvotes: 8

Related Questions