简体   繁体   English

正则表达式在PHP中查找HTML“img”元素的“src”属性

[英]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. 我无法使用正则表达式获取图像URL。 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 它只返回"http://yahoo.com/testfolder/userdata/editoruploadimages/confused

The returned string should be: "http://yahoo.com/testfolder/userdata/editoruploadimages/confused man.jpg" 返回的字符串应为: "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. 读取的部分([^\\s]+)表示选择任何不是空格的东西。

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. 这是一种简单的方法来匹配<img />标签src属性和/或html/PHP内容与正则表达式。

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 仅匹配src属性内容使用

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

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

To match `src' attribute and it content use 匹配`src'属性和它的内容使用

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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