搜索
首页后端开发php教程10 个实用PHP代码片段_PHP教程

10 个实用PHP代码片段_PHP教程

Jul 13, 2016 pm 05:45 PM
functionphp代码作者关键词实用片段高亮

作者:aolinks
关键词高亮

function highlight($sString, $aWords) {
    if (!is_array ($aWords) || emptyempty ($aWords) || !is_string ($sString)) {
        return false;
    }
 
    $sWords = implode ('|', $aWords);
    return preg_replace ('@\b('.$sWords.')\b@si', '$1', $sString);
}


  获取你的Feedburner的用户

function get_average_readers($feed_id,$interval = 7){
    $today = date('Y-m-d', strtotime("now"));
    $ago = date('Y-m-d', strtotime("-".$interval." days"));
    $feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $feed_url);
    $data = curl_exec($ch);
    curl_close($ch);
    $xml = new SimpleXMLElement($data);
    $fb = $xml->feed->entry['circulation'];
 
    $nb = 0;
    foreach($xml->feed->children() as $circ){
        $nb += $circ['circulation'];
    }
 
    return round($nb/$interval);
}

 

  自动生成密码

function generatePassword($length=9, $strength=0) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength >= 1) {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    }
    if ($strength >= 2) {
        $vowels .= "AEUY";
    }
    if ($strength >= 4) {
        $consonants .= '23456789';
    }
    if ($strength >= 8 ) {
        $vowels .= '@#$%';
    }
 
    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i         if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}

 

  压缩多个CSS文件

header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
  /* remove comments */
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  /* remove tabs, spaces, newlines, etc. */
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
  return $buffer;
}
 
/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');
 
ob_end_flush();

 

  获取短网址

function getTinyUrl($url) {
    return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
}

 

  根据生日计算年龄

function age($date){
    $year_diff = '';
    $time = strtotime($date);
    if(FALSE === $time){
        return '';
    }
 
    $date = date('Y-m-d', $time);
    list($year,$month,$day) = explode("-",$date);
    $year_diff = date("Y") – $year;
    $month_diff = date("m") – $month;
    $day_diff = date("d") – $day;
    if ($day_diff  
    return $year_diff;
}

 

  计算执行时间

//Create a variable for start time
$time_start = microtime(true);
 
// Place your PHP/HTML/JavaScript/CSS/Etc. Here
 
//Create a variable for end time
$time_end = microtime(true);
//Subtract the two times to get seconds
$time = $time_end - $time_start;
 
echo 'Script took '.$time.' seconds to execute';

 

  PHP的维护模式

function maintenance($mode = FALSE){
    if($mode){
        if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
            header("Location: http://example.com/maintenance.php");
            exit;
        }
    }else{
        if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
            header("Location: http://example.com/");
            exit;
        }
    }
}

 

  阻止CSS样式被缓存

 

  为数字增加 st\nd\rd 等

function make_ranked($rank) {
    $last = substr( $rank, -1 );
    $seclast = substr( $rank, -2, -1 );
    if( $last > 3 || $last == 0 ) $ext = 'th';
    else if( $last == 3 ) $ext = 'rd';
    else if( $last == 2 ) $ext = 'nd';
    else $ext = 'st'; 
 
    if( $last == 1 && $seclast == 1) $ext = 'th';
    if( $last == 2 && $seclast == 1) $ext = 'th';
    if( $last == 3 && $seclast == 1) $ext = 'th'; 
 
    return $rank.$ext;
}

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478654.htmlTechArticle作者:aolinks 关键词高亮 function highlight($sString, $aWords) { if (!is_array ($aWords) || emptyempty ($aWords) || !is_string ($sString)) { return false; } $sWords = implo...
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何使PHP应用程序更快如何使PHP应用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,关注台词:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能优化清单:立即提高速度PHP性能优化清单:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,关注台词:1)启用opcodeCachingwithapCutoredUcescriptexecutiontime.2)实现databasequerycachingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandredececonnection.4 limitsclection.4.4

PHP依赖注入:提高代码可检验性PHP依赖注入:提高代码可检验性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显着提升了PHP代码的可测试性。 1)DI解耦类与具体实现,使测试和维护更灵活。 2)三种类型中,构造函数注入明确表达依赖,保持状态一致。 3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能优化:数据库查询优化PHP性能优化:数据库查询优化May 12, 2025 am 12:02 AM

databasequeryOptimizationinphpinvolVolVOLVESEVERSEVERSTRATEMIESOENHANCEPERANCE.1)SELECTONLYNLYNESSERSAYCOLUMNSTORMONTOUMTOUNSOUDSATATATATATATATATATATRANSFER.3)

简单指南:带有PHP脚本的电子邮件发送简单指南:带有PHP脚本的电子邮件发送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函数andsupportiveLibrariesLikePhpMailerandSwiftMailer.1)usethemail()functionforbasicemails,butithasimails.2)butithasimimitations.2)

PHP性能:识别和修复瓶颈PHP性能:识别和修复瓶颈May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显着提升PHP应用的性能。

PHP的依赖注入:快速摘要PHP的依赖注入:快速摘要May 11, 2025 am 12:09 AM

依赖性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增强量产生性,可验证性和Maintainability.itallowspasspassingDepentenciesLikEdenceSeconnectionSeconnectionStoclasseconnectionStoclasseSasasasasareTers,interitationApertatingAeseritatingEaseTestingEasingEaseTeStingEasingAndScalability。

提高PHP性能:缓存策略和技术提高PHP性能:缓存策略和技术May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具