http://www.smsyun.com/home-index-page-id-134.html
简单版:
详细版:
01 | <?php |
02 | header( "Content-Type: text/html;charset=utf-8" ); |
03 |
04 | $str = '<div class = "ui-block-a" align= "center" > |
05 | <a href= "online-39.html" ><img class = "lazy" width= "131" height= "177" src= "http://www.smsyun.com/uploads/image/20140620/2014052010425.jpg" /> |
06 | <h3>2014年</h3></a> |
07 | </div>'; |
08 |
09 | $imgpreg = "/<img (.*?) src=\"(.+?)\".*?>/" ; |
10 | preg_match( $imgpreg , $str , $img ); |
11 | $mycount = count ( $img )-1; |
12 | $imgval = $iim [ $mycount ]; |
13 | if (! empty ( $imgval )){ |
14 | echo $imgval ; |
15 | } else { |
16 | echo 'no' ; |
17 | } |
18 | ?> |
详细版:
01 | <?php |
02 | /*PHP正则提取图片img标记中的任意属性*/ |
03 | $str = '<center><img src="/uploads/images/20100516000.jpg" height="120" width="120"><br />PHP正则提取或更改图片img标记中的任意属性</center>' ; |
04 |
05 | //1、取整个图片代码 |
06 | preg_match( '/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i' , $str , $match ); |
07 | echo $match [0]; |
08 |
09 | //2、取width |
10 | preg_match( '/<img.+(width=\"?\d*\"?).+>/i' , $str , $match ); |
11 | echo $match [1]; |
12 |
13 | //3、取height |
14 | preg_match( '/<img.+(height=\"?\d*\"?).+>/i' , $str , $match ); |
15 | echo $match [1]; |
16 |
17 | //4、取src |
18 | preg_match( '/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i' , $str , $match ); |
19 | echo $match [1]; |
20 |
21 | /*PHP正则替换图片img标记中的任意属性*/ |
22 | //1、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/20100516000.jpg") |
23 | print preg_replace( '/(<img.+src=\"?.+)(images\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/i' ,"\${1}uc/images/\${3}", $str ); |
24 | echo "<hr/>" ; |
25 |
26 | //2、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/20100516000.jpg",并省去宽和高 |
27 | print preg_replace( '/(<img).+(src=\"?.+)images\/(.+\.(jpg|gif|bmp|bnp|png)\"?).+>/i' ,"\${1} \${2}uc/images/\${3}>", $str ); |
28 | ?> |