要匹配的字符串:<img src=image/ad1.gif width='128' height='36'/><img src='image/ad2.gif' width='128' height='36' /> 提取的结果: image/ad1.gif PHP正则提取或替换img标记属性 <?php /*PHP正则提取图片img标记中的任意属性*/ $str = '<center><img src='/uploads/images/20100516000.jpg' height='120' width='120'><br />PHP正则提取或更改图片img标记中的任意属性</center>'; //1、取整个图片代码 preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\')(.*?)\\1[^>]*?\/?\s*>/i',$str,$match); echo $match[0]; //2、取width preg_match('/<img.+(width=\'?\d*\'?).+>/i',$str,$match); echo $match[1]; //3、取height preg_match('/<img.+(height=\'?\d*\'?).+>/i',$str,$match); echo $match[1]; //4、取src preg_match('/<img.+src=\'?(.+\.(jpg|gif|bmp|bnp|png))\'?.+>/i',$str,$match); echo $match[1]; /*PHP正则替换图片img标记中的任意属性*/ //1、将src='/uploads/images/20100516000.jpg'替换为src='/uploads/uc/images/20100516000.jpg') print preg_replace('/(<img.+src=\'?.+)(images\/)(.+\.(jpg|gif|bmp|bnp|png)\'?.+>)/i','\${1}uc/images/\${3}',$str); echo '<hr/>'; //2、将src='/uploads/images/20100516000.jpg'替换为src='/uploads/uc/images/20100516000.jpg',并省去宽和高 print preg_replace('/(<img).+(src=\'?.+)images\/(.+\.(jpg|gif|bmp|bnp|png)\'?).+>/i','\${1} \${2}uc/images/\${3}>',$str); ?> Js正则表达式提取图片地址 JavaScript使用正则表达式和Replace两种方法提取IMG标签图片地址,代码如下: /正则表达式<script language='javascript'>var a='<P><IMG src='http://bbs.cn./user_img/200701/31/jisuanji986_117025184198149.jpg' mce_src='http://bbs.cn./user_img/200701/31/jisuanji986_117025184198149.jpg'></P>'var b=/<IMG src=\'([^\']*?)\'>/givar s=a.match(b)for(var i= 0;i<s.length;i++){alert(s[i]);alert(RegExp.$1)}</script> 还有一种方法,是用的replace替换法,不知对不,我不是JS高手: <script language='javascript'>var a='<P><IMG src='http://bbs.cn./user_img/200701/31/jisuanji986_117025184198149.jpg' mce_src='http://bbs.cn./user_img/200701/31/jisuanji986_117025184198149.jpg'></P>'var b=/<IMG src=\'([^\']*?)\'>/givar s=a.match(b)for(var i= 0;i<s.length;i++){alert(s[i]);alert(s[i].replace(b,'$1'))}</script> |
|