PHP正則提取圖片img標記中的任意屬性

/*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); 




<?php
/*PHP正則提取圖片img標記中的src屬性*/ 
$str = '<center><img src="//img.w3cschool.cn/attachments/image/animals.png"><br />PHP正則提取或更改圖片img標記中的任意屬性</center>'; 



//4、取src 
preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$str,$match); 
$src = $match[1];

$filename_index = strripos($src, '/');
$filename = substr($src,$filename_index+1);

$host_index = stripos($src,'//img.w3cschool.cn');
if ($host_index === 0) {
    $imgdir = substr($src, 18, $filename_index-18);
} else if($host_index === FALSE){
    $imgdir = substr($src, 0, $filename_index);
}
print_r($imgdir);


$src_arr = explode('/', $src);
print_r($src_arr);


echo $filename;











發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章