欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP正則獲取頁面所有圖片地址

 更新時間:2016年03月23日 09:12:23   作者:jerrylsxu  
這篇文章主要介紹了PHP正則獲取頁面所有圖片地址 的相關(guān)資料,需要的朋友可以參考下
<?php
//取得頁面所有的圖片地址
function getimages($str)
{
$match_str = "/((http://)+([^ rn()^$!`"'|[]{}<>]*)((.gif)|(.jpg)|(.bmp)|(.png)|(.GIF)|(.JPG)|(.PNG)|(.BMP)))/";
preg_match_all ($match_str,$str,$out,PREG_PATTERN_ORDER);
return $out;
}
?> 

/<img.*srcs*=s*["|']?s*([^>"'s]*)/i

,我使用kindeditor保存文章,但是需要取出第N個圖片的地址作為文章的標志圖片,文章代碼(內(nèi)容的html)保存到數(shù)據(jù)庫一個字段,然后圖片地址保存到另外一個字段.我就是使用上面的正則解決的.

我說明下,上面的地址是直接獲取img標簽內(nèi)src屬性的值.在使用該正則的php頁面訪問該路徑如果能找到圖片的話,可以直接使用,如果不能,你可以使用preg_match_all將所有地址先保存到數(shù)組,然后處理路徑,比如獲取文件名稱(不含路徑部分),然后重新組成url,再刪除圖片.

我的例子:

preg_match_all("/<img.*srcs*=s*["|']?s*([^>"'s]*)/i",str_ireplace("\","",$content),$arr); 

呵呵 我的內(nèi)容部分被php給加上轉(zhuǎn)義了,所以我需要先把去除,str_ireplace("\","",$content),然后將匹配的內(nèi)容保存到$arr數(shù)組(二維的).

$arr[1]就是存儲該路徑的數(shù)組.

實例

<?php
$ext = 'gif|jpg|jpeg|bmp|png';//羅列圖片后綴從而實現(xiàn)多擴展名匹配 by http://www.dbjr.com.cn 綠色軟件
$str = '<p><img title="綠色軟件" alt="綠色軟件" onload="ResizeImage(this,860)" src="http://www.dbjr.com.cn /data/soft_img/2010091101619.jpg" /></p><p><img title="綠色軟件" alt="綠色軟件" onload="ResizeImage(this,860)" src="http://www.dbjr.com.cn /data/soft_img/2010091029938.jpg" /></p><p><img title="綠色軟件" alt="綠色軟件" onload="ResizeImage(this,860)" src="http://www.dbjr.com.cn /data/soft_img/2010092839019.jpg" /></p>';
preg_match_all("/(href|src)=(["|']?)([^ "'>]+.($ext))\2/i", $str, $matches);
var_dump($matches);
?> 

結(jié)果

array(5) {
[0]=>
array(3) {
[0]=>
string(57) "src="http://www.dbjr.com.cn /data/soft_img/2010091101619.jpg""
[1]=>
string(57) "src="http://www.hzhuti.com/sonyericsson/w715/ 2010091029938.jpg""
[2]=>
string(57) "src="http://www.dbjr.com.cn /data/soft_img/2010092839019.jpg""
}
[1]=>
array(3) {
[0]=>
string(3) "src"
[1]=>
string(3) "src"
[2]=>
string(3) "src"
}
[2]=>
array(3) {
[0]=>
string(1) """
[1]=>
string(1) """
[2]=>
string(1) """
}
[3]=>
array(3) {
[0]=>
string(51) "http://www.dbjr.com.cn /data/soft_img/2010091101619.jpg"
[1]=>
string(51) "http://www.dbjr.com.cn /data/soft_img/2010091029938.jpg"
[2]=>
string(51) "http://www.dbjr.com.cn /data/soft_img/2010092839019.jpg"
}
[4]=>
array(3) {
[0]=>
string(3) "jpg"
[1]=>
string(3) "jpg"
[2]=>
string(3) "jpg"
}
}

PHP正則匹配圖片并給圖片加鏈接詳解

$newstext=preg_replace(preg_replace('/(<img[^>]+srcs*=s*”?([^>"s]+)”?[^>]*>)/im', ‘<a href=”$2″>$1</a>', $newstext); 

1.preg_replace和str_replace的區(qū)別:

str_replace只是純字符替換,而preg_replace才是正則替換

2.$0,$1,$2等的說明:

$0指的是被整個模式所匹配的文本;

$1指的是首個 ( ) 引用的串;

$2指的是第二個()引用的串; 以此類推

有關(guān)PHP正則獲取頁面所有圖片地址的知識,小編就給大家介紹到這里,希望對大家有所幫助!

相關(guān)文章

最新評論