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

时间:2013-06-18 08:24:22

标签: php html regex

我有一个字符串,里面有我的图像:

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

我无法使用正则表达式获取图片网址。我的代码是:

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

此代码在遇到图像名称中的空格时停止执行。它只返回"http://yahoo.com/testfolder/userdata/editoruploadimages/confused

返回的字符串应为: "http://yahoo.com/testfolder/userdata/editoruploadimages/confused man.jpg"

4 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:8)

读取([^\s]+)的部分意味着选择任何不是空格的内容。

也许尝试类似的事情:

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

选择任何不是双引号的东西。

答案 2 :(得分:1)

感谢每一个人帮助我。

我使用以下方法找到了我的解决方案:

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

答案 3 :(得分:1)

以下是一种简便方法,可以将<img />代码src属性和/ html/PHP中的内容与正则表达式进行匹配。

样品:

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

仅匹配src属性内容使用

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

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

要匹配`src'属性,请使用

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

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