BigToach.com

PHP Snippets

1 ... « 9 10 11

timer

Information

(PHP Version >= 4.0.4)
Functions used in this snippet: array_sum, microtime, explode, number_format.

Description

float timer([float start,[int num]])

sets a start timer and outputs another timer less start to num decimals.

Snippet

<?php
function timer($start='',$num=8){
    if(
$start === ''){
        return 
array_sum(explode(' ',microtime()));
    }else{
        return 
number_format(timer() - $start,$num);
    }
}
?>

Example

timer Can be used in the following way:

<?php
$start 
timer();
// code to be timed goes here
echo timer($start); // shows elapsed time to 8 decimal places

$start timer();
// code to be timed goes here
echo timer($start,12); // shows elapsed time to 12 decimal places
?>

Added on Jun 23rd at 9 pm by Scott - 0 Comments
Updated on Jul 1st at 4 am.


stri_replace

Information

(PHP Version >= 4.10)
Functions used in this snippet: array_key_exists, count, is_array, array_keys, strtolower, str_replace, explode, strlen, substr.

Description

str stri_replace(mixed search, mixed replace, str subject)

replaces all occurances of search with replace in the subject string and returns the corrected string. It is done without regards to text case.

search and replace can bot be arrays.

Snippet

<?php
function stri_replace($word,$replace,$str){
    
$wordray is_array($word) ? true false;
    
$replray is_array($replace) ? truefalse;
    if(
$wordray){
        
$wordkeys array_keys($word);
        
$sizeword count($wordkeys);
        if(
$replray){
            
$replkeys array_keys($replace);
            
$sizerepl count($replace);
        }
        for(
$i=0$i<$sizeword$i++){
            if(
$replray && array_key_exists($i,$replkeys)){
                
$repll $replace[$replkeys[$i]];
            }elseif(
$replray){
                
$repll '';
            }else{
                
$repll $replace;
            }
            
$str stri_replace($word[$wordkeys[$i]],$repll,$str);
        }
        
$ret $str;
    }else{
        
$str_low strtolower($str);
        
$word_low strtolower($word);
        
$str_low str_replace($word_low,$word,$str_low);
        
$explode explode($word,$str_low);
        
$count count($explode);
        
$ret '';
        
$holder 0;
        
$len strlen($word);
        for(
$i=0$i<$count$i++){
            
$thislen strlen($explode[$i]);
            
$ret .= substr($str,$holder,$thislen);
            if(
$i !== ($count 1)){
                
$ret .= $replace;
            }
            
$holder $holder $thislen $len;
        }
    }
    return 
$ret;
}
?>

Example

stri_replace Can be used in the following way:

<?php
$str 
'I HAte Red and love Blue';
echo 
stri_replace('hate','despise',$str); // I despise Red and love Blue
echo stri_replace(array('hate','LOVE'), array('enjoy','despise'),$str);
// I enjoy Red and despise Blue
?>

Added on Jun 23rd at 9 pm by Scott - 1 Comment
Updated on Jun 25th at 1 am.


1 ... « 9 10 11