`
phantom
  • 浏览: 160265 次
社区版块
存档分类
最新评论

php 正则表达式的是一个使用范例 统计链接生成与替换

阅读更多
<?php

class acmeCache{

 function fetch($name, $refreshSeconds = 0){

  if(!$GLOBALS['cache_active']) return false;
  if(!$refreshSeconds) $refreshSeconds = 60;
  $cacheFile = acmeCache::cachePath($name);
  if(file_exists($cacheFile) and
   ((time()-filemtime($cacheFile))< $refreshSeconds))
   $cacheContent = file_get_contents($cacheFile);
  return $cacheContent;
 }

 function save($name, $cacheContent){
  if(!$GLOBALS['cache_active']) return;
  $cacheFile = acmeCache::cachePath($name);
  acmeCache::savetofile($cacheFile, $cacheContent);
 }

 // for internal use
 // ====================
 function cachePath($name){
  $cacheFolder = $GLOBALS['cache_folder'];
  if(!$cacheFolder) $cacheFolder = trim($_SERVER['DOCUMENT_ROOT'],'/').'/cache/';
  return $cacheFolder . md5(strtolower(trim($name))) . '.cache';
 }

 function savetofile($filename, $data){
  $dir = trim(dirname($filename),'/').'/';
  acmeCache::forceDirectory($dir);
  $file = fopen($filename, 'w');
  fwrite($file, $data); fclose($file);
 }

 function forceDirectory($dir){ // force directory structure
  return is_dir($dir) or (acmeCache::forceDirectory(dirname($dir)) and mkdir($dir, 0777));
 }

}
function repHtml($data){
//$pattern = "|·<a href=(.*) target=_blank>(.*)</a>|Us"; //表格内的行
  $pattern = "|<a href=\"http://(.*)\"|Us"; //表格内的行
//  preg_match_all($pattern,$data,$matches);
//
  $data=preg_replace($pattern, '<a href="ad.php?p=$1"',$data);

//  foreach($matches[1] as $key =>$value)
//{
////echo $value."\n";
//}
  return $data;
}
$cache_active = true;
$cache_folder = 'cache/';
$key="zhuanti/share/intr.shtml";
 $result = acmeCache::fetch($key, 300+rand()%1); // 2-4分钟
  {
  	$data = file_get_contents ("http://www.jinghua.cn/zhuanti/share/intr.shtml");
     $result =  repHtml($data);
     acmeCache::save($key, $result);
  }

  echo $result;



?>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics