日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

php 实现类,php 获取页面中指定内容的实现类

發布時間:2023/12/4 php 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 php 实现类,php 获取页面中指定内容的实现类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文為大家下使用php如何獲取頁面中的指定內容,而且以封裝成類,需要的朋友可以參考下本文

功能:

1.獲取內容中的url,email,image。

2.替換內容中的url,email,image。

url:xxx

email:admin@admin.com

image:

Grep.class.php

/** grep class

* Date: 2013-06-15

* Author: fdipzone

* Ver: 1.0

*

* Func:

*

* set: 設置內容

* get: 返回指定的內容

* replace: 返回替換后的內容

* get_pattern 根據type返回pattern

*/

class Grep{ // class start

private $_pattern = array(

'url' => '/

'email' => '/([\w\-\.]+@[\w\-\.]+(\.\w+))/',

'image' => '//i'

);

private $_content = ''; // 源內容

/* 設置搜尋的內容

* @param String $content

*/

public function set($content=''){

$this->_content = $content;

}

/* 獲取指定內容

* @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();

}

/* 獲取替換后的內容

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

}

/* 根據type獲取pattern

* @param String $type

* @return String

*/

private function get_pattern($type){

return $this->_pattern[$type];

}

} // class end

?>

Demo

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]' : '';

}

?>

總結

以上是生活随笔為你收集整理的php 实现类,php 获取页面中指定内容的实现类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。