php - 求正则,获取图片src的地址
巴扎黑
巴扎黑 2017-04-11 09:18:16
[PHP讨论组]

<img src=image/ad1.gif width="128" height="36"/>
<img src='image/ad2.gif' width="128" height="36" />
<img src=\'image/ad3.gif\' width="128" height="36" />
<img src="image/ad4.gif" width="128" height="36" />
<img src=\"image/ad5.gif\" width="128" height="36" />

正则取上述代码内src的值
image/ad1.gif
image/ad2.gif
image/ad3.gif
image/ad4.gif
image/ad5.gif

巴扎黑
巴扎黑

全部回复(9)
阿神

获取src的值str,然后 str.match(/image(S*)gif/)[0]

$('img').each(function(index,item){
    console.log(item.src.match(/image(\S*)gif/)[0]);
})
天蓬老师
/src=(?:pattern'|\"|\\\['"]|\\\)?(.*?)(?:pattern'|\"|\\\['"]|\\\)?\sw/

我也不知道正不正确

巴扎黑

大家讲道理
//如果你的src中肯定不包含空格的话可以用这个简单的办法,通常是ok的
preg_match_all('/<img src=([^ \t]+)/', $str, $_match);

这样得到的内容会包含单引号什么的,对于带有反斜线的单双引号先去掉反斜线,然后trim一下就行了,例如

foreach($_match[1] as str) {
    $str = str_replace("\\'", "'", $str);
    $str = str_replace('\\"', '"', $str);
    echo trim($str, '\'"');
}

大致这样,具体的自己调试吧。不太复杂的正则匹配优先考虑关键字符来排除结果,比如本例中的空格及制表符。

阿神

http://tool.oschina.net/regex/

<img[^>]*?src=\\?["]?(.*?)["]?\s[^>]*?>

此处应该有红包

黄舟

高洛峰
$rule = '#<img\s+src=([^\s]*).*?\/>#';
ringa_lee

你可以试试:在线正则表达式生成工具

阿神

我的好像直接就对了

<?php
$str = <<<EOT
<img src=image/ad1.gif width="128" height="36"/>
<img src='image/ad2.gif' width="128" height="36" />
<img src=\'image/ad3.gif\' width="128" height="36" />
<img src="image/ad4.gif" width="128" height="36" />
<img src=\"image/ad5.gif\" width="128" height="36" />
EOT;

preg_match_all("/src=\\\\?[\\\"']?([\\w\\.\\/-]*)\\\\?[\\\"']?\s/", $str, $arr);
var_dump($arr[1]);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号