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

作者: 范云力  本站原创  发布时间:  浏览:32次

 

功能:


1.获取内容中的url,email,image。


2.替换内容中的url,email,image。


url:<a href="url">xxx</a>


email:admin@admin.com


image:<img src=//img.aniys.com/skin/image/nopic.gif>




Grep.class.php


<?php

 

class Grep{ // class start

 

    private $_pattern = array(

                            'url' => '/<a.*?href="((http(s)?:\/\/).*?)".*?/si',

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

                            'image' => '/<img.*?src=//img.aniys.com/skin/image/nopic.gif'

                        );

 

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

 

 

   

    public function set($content=''){

        $this->_content = $content;

    }

 

 

   

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

 

    }

 

 

   

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

 

    }

 

 

   

    private function get_pattern($type){

        return $this->_pattern[$type];

    }

 

 

} // class end

 

?>

Demo

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

}

?> 

相关文章

新手指南支付购买售后服务关于我们
阿力盈商网络科技有限公司
Copyright 2002-2019 网 版权所有
渝ICP备18009082号网站地图
热门TAG:下拉导航

首页

电话咨询

客服QQ