經(jīng)常和圖片打交道,不得不用到一些提取圖片中scr、alt、title、等的屬性,這里總結(jié)給大家一些常用的,感覺還不錯,比較通用!
PHP正則表達(dá)式匹配img中任意屬性PHP
/*PHP正則提取圖片img標(biāo)記中的任意屬性*/
$str = ‘<center><img src=”/uploads/images/20100516000.jpg” height=”120″ width=”120″><br />PHP正則提取或更改圖片img標(biāo)記中的任意屬性</center>’;
//1、取整個(gè)圖片代碼
preg_match(‘/<s*imgs+[^>]*?srcs*=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]; (PS:T不錯的php Q扣n:276167802,驗(yàn)證:csl)
/*PHP正則替換圖片img標(biāo)記中的任意屬性*/
//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);
?>
PS:關(guān)于正則,本站還提供了2款非常簡便實(shí)用的正則表達(dá)式在線工具供大家參考使用:
JavaScript正則表達(dá)式在線測試工具:http://tools.jb51.net/regex/javascript
正則表達(dá)式在線生成工具:http://tools.jb51.net/regex/create_reg