简体   繁体   中英

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"

我会抓住引号内的所有内容:

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

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.

Thank every one for helping me out.

I found my solution by using:

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM