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

本文介绍了一个简单的PHP缓存类实现,包括缓存获取与存储功能,并演示了如何使用该类来缓存网页内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



?>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值