溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

利用php怎么獲取頁面中的指定內(nèi)容

發(fā)布時間:2020-12-25 15:30:36 來源:億速云 閱讀:384 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹利用php怎么獲取頁面中的指定內(nèi)容,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

功能:
1.獲取內(nèi)容中的url,email,image。
2.替換內(nèi)容中的url,email,image。
url:<a href="url">xxx</a>

email:admin@admin.com

image:<img src="image">

Grep.class.php

復(fù)制代碼 代碼如下:


<?php
/** grep class
* Date: 2013-06-15
* Author: fdipzone
* Ver: 1.0
*
* Func:
*
* set: 設(shè)置內(nèi)容
* get: 返回指定的內(nèi)容
* replace: 返回替換后的內(nèi)容
* get_pattern 根據(jù)type返回pattern
*/

class Grep{ // class start

private $_pattern = array(
'url' => '/<a.*?href="((http(s)?:\/\/).*?)".*?/si',
'email' => '/([\w\-\.]+@[\w\-\.]+(\.\w+))/',
'image' => '/<img.*?src=\"(http:\/\/.+\.(jpg|jpeg|gif|bmp|png))\">/i'
);

private $_content = ''; // 源內(nèi)容


/* 設(shè)置搜尋的內(nèi)容
* @param String $content
*/
public function set($content=''){
$this->_content = $content;
}


/* 獲取指定內(nèi)容
* @param String $type
* @param int $unique 0:all 1:unique
* @return Array
*/
public function get($type='', $unique=0){

$type = strtolower($type);

if($this->_content=='' || !in_array($type, array_keys($this->_pattern))){
return array();
}

$pattern = $this->get_pattern($type); // 獲取pattern

preg_match_all($pattern, $this->_content, $matches);

return isset($matches[1])? ( $unique==0? $matches[1] : array_unique($matches[1]) ) : array();

}


/* 獲取替換后的內(nèi)容
* @param String $type
* @param String $callback
* @return String
*/
public function replace($type='', $callback=''){

$type = strtolower($type);

if($this->_content=='' || !in_array($type, array_keys($this->_pattern)) || $callback==''){
return $this->_content;
}

$pattern = $this->get_pattern($type);

return preg_replace_callback($pattern, $callback, $this->_content);

}


/* 根據(jù)type獲取pattern
* @param String $type
* @return String
*/
private function get_pattern($type){
return $this->_pattern[$type];
}
} // class end

?>


Demo

復(fù)制代碼 代碼如下:


<?php
header('content-type:text/htm;charset=utf8');

require('Grep.class.php');

$content = file_get_contents('http://www.test.com/');

$obj = new Grep();
$obj->set($content);

$url = $obj->get('url', 0);
$email = $obj->get('email', 1);
$image = $obj->get('image', 1);

print_r($url);
print_r($email);
print_r($image);

$url_new = $obj->replace('url', 'replace_url');
echo $url_new;

function replace_url($matches){
return isset($matches[1])? '[url]'.$matches[1].'[/url]' : '';
}
?>

關(guān)于利用php怎么獲取頁面中的指定內(nèi)容就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI