jueves, septiembre 27, 2012


Googleando , encontré algunos tips que pueden salvarte la vida cuando estas codificando en PHP.
Me pareció interesante la lista que detallo a continuación.



Resaltar determinada palabra en un párrafo:
Al mostrar los resultados de búsqueda, es buena idea para resaltar palabras específicas.

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', '$1', $sString);
}

Creación automática de password
En los procesos de automatizacion es necesario generar una contraseña automatica para luego reemplazarla por la del usuario, esta es la funcion:

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


Comprimir múltiples archivos CSS:
Si estas empleando diferentes CSS en el desarrollo de un sitio, probablemente estos te esten consumiendo tiempo de carga.
Empleando PHP se puede comprimir estos en un archivo simple, quitando espacios y comentarios innecesarios.

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



Direcciones Cortas para  Twitter
Estas usando bit.ly o tinyurl para acortar direcciones, por que no emplearlo para tu posteos en tu blog automaticamente?


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


Calcular la edad usando fecha de nacimiento:
Es un clasico, quien no tuvo alguna vez que hacer el calculo...

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

Calcular tiempo de ejecucion
Orientado para debug y mejorar el rendimiento del codigo

//Create a variable for start time
$time_start = microtime(true);

// Ubicar PHP/HTML/JavaScript/CSS/Etc. aqui

//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


Modo mantenimiento en PHP
Habilitar una pagina de mantenimiento por cualquier tipo de trabajo que estes realizando en un sitio, da un toque profesional a tus desarrollos.
Este codigo, te excime de emplear .htaccess solo con 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

Prevenir que los archivos js y css sean Cacheados (copiados al Cache)


Se veria de la forma:


Source: http://davidwalsh.name/prevent-cache


Quitar tags HTML de una Cadena

$text = strip_tags($input, "");
Source:http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2


Transformar una URL a hyperlink:

$url = "Jean-Baptiste Jung (http://www.webdevcat.com)";
$url = preg_replace("#http://([A-z0-9./-]+)#", '$0', $url);

Source:http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2


Quitar URLs de cadenas de texto:

$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);
Source: http://snipplr.com/view.php?codeview&id=15236


Buscar una cadena dentro de otra:

function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
        $str = strtolower($str);
        $content = strtolower($content);
    }
    return strpos($content,$str) ? true : false;
}
Source:http://www.jonasjohn.de/snippets/php/contains.htm

Extraer y filtrar emails de una cadena de texto:

function extract_emails($str){
    // This regular expression extracts all emails from a string:
    $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    preg_match_all($regexp, $str, $m);

    return isset($m[0]) ? $m[0] : array();
}

$test_string = 'This is a test string...

        test1@example.org

        Test different formats:
        test2@example.org;
        foobar
       

        strange formats:
        test5@example.org
        test6[at]example.org
        test7@example.net.org.com
        test8@ example.org
        test9@!foo!.org

        foobar
';

print_r(extract_emails($test_string));



No hay comentarios: