Highlight specific words in a phrase
Sometimes, for example, when displaying search results, it is a great idea to highlight specific words. This is exactly what the following function can do:
function highlight($sString, $aWords) {
if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
return false;
}
$sWords = implode ('|', $aWords);
return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
}Source: http://www.phpsnippets.info/highlights-words-in-a-phrase
Get your average Feedburner subscribers
Recently, Feedburner counts had lots of problems and it’s hard to say that the provided info is still relevant. This code will grab your subscriber count from the last 7 days and will return the average.
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);
}Source: http://www.catswhoblog.com/how-to-get-a-more-relevant-feedburner-count
Automatic password creation
Although I personally prefer leaving users to choose their password themselves, a client recently asked me to generate passwords automatically when a new account is created.
The following function is flexible: You can choose the desired length and strength for the password.
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 < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}Source: http://www.phpsnippets.info/generate-a-password-in-php
Compress multiple CSS files
If you’re using different CSS files on your site, they might take quite long to load. Using PHP, you can compress them into a single file with no unnecessary white spaces or comments.
This snippet has been previously discussed on my “3 ways to compress CSS files using PHP” article.
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();Source: http://www.phpsnippets.info/compress-css-files-using-php
Get short urls for Twitter
Are you on Twitter? If yes, you probably use a url shortener such as bit.ly or TinyUrl to share your favorite blog posts and links on the network.
This snippet take a url as a parameter and will return a short url.
function getTinyUrl($url) {
return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
}Source: http://www.phpsnippets.info/convert-url-to-tinyurl
Calculate age using date of birth
Pass a birth date to this function, and it will return the age of the person; very useful when building communities or social media sites.
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 < 0 || $month_diff < 0) $year_diff–;
return $year_diff;
}Source: John Karry on http://www.phpsnippets.info/calculate-age-of-a-person-using-date-of-birth
Calculate execution time
For debugging purposes, it is a good thing to be able to calculate the execution time of a script. This is exactly what this piece of code can do.
//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';
Source: http://phpsnips.com/snippet.php?id=26
Maintenance mode with PHP
When updating your site, it is generally a good thing to temporarily redirect your users to a “Maintenance” page so they will not see any critical info such as error messages.
This is generally done using an .htaccess file, but it can be done easily with 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;
}
}
}Source: http://www.phpsnippets.info/easy-maintenance-mode-with-php
Prevent js and css files from being cached
By default, external files such as javascript and css are cached by the browser. If you want to prevent this from caching, simply use this easy tip:
<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" /&glt;
The result will look like this:
<link href="/stylesheet.css?1234567890" rel="stylesheet" type="text/css" /&glt;
Source: http://davidwalsh.name/prevent-cache
Add (th, st, nd, rd, th) to the end of a number
Another useful snippet which will automatically add st, nd, rd or th after a number.
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;
}Source: http://phpsnips.com/snippet.php?id=37






My name is Jean-Baptiste Jung and I'm the man behind Cats Who Code. I started to use the Internet back in 1998 and started to create websites three years laters in 2001.
36 Comments
“Prevent js and css files from being cached”
The best way to prevent this, is copy the Rails helper mode.
link href=”/stylesheet.css?” rel=”stylesheet” type=”text/css”
The Wordpress remove my code.
Use the function filemtime.
“/stylesheet.css?filemtime(stylesheet.css);”
filemtime() is much better, except that on high-load websites, it can use too much processing.
Another alternative is to use the current revision number or hash for your current live version of your repository.
Why would you guys prevent caching. I force caching with .htaccess
Thanks.
By the way, I like the execution time calculator
Awesome!
I’m always partial to the include.
can’t live without it
-TK
Google is my “web developer toolbox” – thanks for publishing some sweet code snippets to the index
Shak
Some of the snippets are more like features rather than life saving. Good resource to have though.
Thanks
Re: Add (th, st, nd, rd, th) to the end of a number
Why not:
$n = 9;
echo date($n.’S');
Because without a timestamp date() will use the current time.
So if it’s say the first of the month you’ll end up with “9st”.
You’d have to construct a timestamp using mktime() and pass that as the second parameter to get an accurate suffix.
Which would still be much shorter than the suggested method, although not sure if there would be any performance hit by using mktime() and date() – something to look into methinks.
Actually, about that last method – I’m surprised there’s no use of MOD (%) to get the last number or ‘teenth’ status, or a switch when checking the numbers – far to many elses.
RE caching of CSS files, surely one would want them cached to save time and bandwidth? The best thing to do is slap a version number on the end i.e. style.css?v=1.1.5, that way it will be redownloaded when changed, but all other times the cached version (if far future expires has been used) will be used – if developing just hit ctrl+f5.
Echo date(’jS’, strtotime(’0000-00-’.$day))
I guess I meant more along:
echo date(’jS’, strtotime(’0000-00-’.$nDay));
bad hack still
all very good tips.
re: Compress multiple CSS files, great tip, but you are going to be loading and compressing the files each time the page loads, I would suggest using this function on your site once completed, outputting the result to a file (style.min.css) and then loading that. Use apache gzip to compress it. Much less strain on the web server.
great stuff now bookmarked Thanks for sharing
Thanks alot, needed the word highlighting, will test later, hopefully it can cope with phrases too
echo ‘Script took ‘.$time.’ seconds to execute’;
should be
echo ‘Script took ‘.$time.’ microseconds to execute’;
No, it’s labeled correctly. microtime(true) returns the UNIX time *with* microseconds as a float.
Awesome, thanks a lot for sharing!
Why on the “Automatic password creation” are the vowels not all vowels, and missing some and why is $consonants missing some as well?
To prevent ambiguous characters from being used. It’s difficult to tell 0 from O (zero from “o”), or I from l (capital “i” from lower-case “L”).
Nice tips, definitely handy.
Regarding CSS multiple file compression, how does one differentiate between ‘print’ style and ‘main’ style. I assume these styles contain some identical elements and whatever comes later will be displayed.
Normally we provide a media attribute, but what happens here??
Great php code samples, nice coding. “Calculate execution time” really came handy for my Joomla website, it is really heavy and it requires value of 150 which I didn’t know previous. Great tips, thanks.
I thought I was stuck with the site error page during maintenance and found myself very annoyed and also stressed that a potential customer would come across it. I have implemented the snipped with the .htaccess file and voila – now I’m doing “site maintenance” Thanks!!
true, but i got poor skill on coding:(, hopefully can learn much from this site
Many thanks. There are 3 or 4 listed which for me are great to have around. I love the ‘Swiss pen knife’ aspect of have all these code snippets at my disposal.
Great snippets and coding tips, for sure I need to use some of those. Previously I was building websites from scratch, but now all those open source CMS are simply amazing.
Nice list of php functions dude!
I like the date of birth and the word highlighter one the best.
Keep up the good code!
Lacey Tech Solutions
About the highlight function: I think it’s better if it returns the original string, when $aWords is empty. Otherwise, if there’s nothing to highlight, nothing will be returned.
I’d rather use cURL than file_get_contents for remote urls tho.
The automatic password is genius. I never knew it was possible with just some ’simple’ php code. I added it to a website of mine. Many thanks.
Great tips, thanks for sharing.
I love resources like this. Whenever I’m into a project, there’s nothing more I hate than having to re-invent the wheel to do something common.
the highlight shows errors on my website in the error_log file, it works fine for me however I view the error_log and a few customers must have triggered the error. Why?
Did they search for a | or something to make it… funny?
Yes, the error was probably caused by somebody searching for a word containing “|”. On many keyboard layouts the “|” key is beside the shift key and could be hit by mistake. It is also possible they were intentionally searching for “|” but that is unlikely outside of programming related sites.
The easiest fix is to just strip “|” characters from the $aWords array.
really really nice.
I never knew it was possible with just some ’simple’ php code.I love the ‘Swiss pen knife’ aspect of have all these code snippets at my disposal.
well, it didn’t displayed correctly, I remove the opening php tags :
/**
* Create a DateTime object with the given number of seconds
*
* @param Integer $iTime : Timestamp in seconds
* @param String $sFormat (optionel) : The date format to return
*
* @return String : The formated date
*/
function timetostr ($iTime, $sFormat = ‘d\j H\hi\ms\s’) {
$oTime = new DateTime (’@’.$iTime);
return $oTime->format ($sFormat);
}
and the adptated snippet :
timetostr (strtotime($date), ‘Y’);
7 Trackbacks
[...] 10 life-saving PHP snippets Posted July 19th, 2010 in Blog by Gareth http://www.catswhocode.com/blog/10-life-saving-php-snippets?utm_source=twitte…; [...]
=== popurls.com === popular today…
yeah! this story has entered the popular today section on popurls.com…
[...] Cats who code – PHP snippets [...]
[...] http://www.catswhocode.com/blog/10-life-saving-php-snippets Like Unlike share this with your people [...]
[...] 10 life-saving PHP snippets [...]
[...] 10 life-saving PHP snippets [...]
[...] Cats who code has a great article on ‘10 life saving PHP snippets’. [...]