Skip navigation

Tag Archives: php snippets

First of all i would like to thanks to this blog ( http://www.catswhocode.com/blog/10-life-saving-php-snippets ) for giving this very nice php snippets info to keep. (w/c took me to other php site codes to ponder)  I am not a hardcoder of php so i would like to keep this one for my future references. Now, time to go through my notes…

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

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

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 maintenance($mode = FALSE){
if($mode){
if(basename($_SERVER[‘SCRIPT_FILENAME’]) != ‘maintenance.php’){
header(“Location: http://example.com/maintenance.php&#8221;);
exit;
}
}else{
if(basename($_SERVER[‘SCRIPT_FILENAME’]) == ‘maintenance.php’){
header(“Location: http://example.com/&#8221;);
exit;
}
}
}

  • HIGHLIGHT SPECIFIC WORDS IN A PHRASE – Sometimes it can be really usefull for a visitor to have the terms he serached for highlighted. The following snippet is using a simple regular expression to find words in a phrase and highlight them.
  • http://www.phpsnippets.info/highlights-words-in-a-phrase

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);
}

Well so far these are the snippets that i needed most and I wanna keep on my blog. And If you guys need more of the codes then you can just click on the links above for more of it. 🙂

Advertisements