Function:
1. Get the url,email,image in the content.
2. Replace the url,email,image in the content.
Url:xxx
Email:admin@admin.com
Image
Grep.class.php
Copy CodeThe code is as follows:
/** grep class
* DATE:2013-06-15
* Author:fdipzone
* ver:1.0
*
* Func:
*
* Set: Setting content
* Get: Returns the specified content
* Replace: Returns the replaced content
* Get_pattern returns pattern according to type
*/
Class grep{//Class start
Private $_pattern = Array (
' url ' = = '/' email ' + '/([\w\-\.] +@[\w\-\.] + (\.\w+))/',
' Image ' = '//i '
);
Private $_content = '; Source content
/* Set Search Content
* @param String $content
*/
Public function set ($content = ") {
$this->_content = $content;
}
/* Get the specified 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); Get pattern
Preg_match_all ($pattern, $this->_content, $matches);
return Isset ($matches [1])? ($unique ==0? $matches [1]: Array_unique ($matches [1]): Array ();
}
/* Get the replaced content
* @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);
}
/* Get pattern based on type
* @param String $type
* @return String
*/
Private Function Get_pattern ($type) {
return $this->_pattern[$type];
}
}//Class end
?>
Demo
Copy CodeThe code is as follows:
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] ': ';
}
?>
http://www.bkjia.com/PHPjc/726021.html www.bkjia.com true http://www.bkjia.com/PHPjc/726021.html techarticle features: 1. Get the url,email,image in the content. 2. Replace the url,email,image in the content. url:a href= "url" xxx/a email:admin@admin.com image:img src= "image" Grep.class.ph ...