» » » Несколько полезных сниппетов на php

Несколько полезных сниппетов на php

21-04-2015, 00:10
Автор: .
Просмотров: 1 042
Комментариев: 0
Версия для печати
Несколько полезных сниппетов на php

Мелочи, а упрощают жизнь.
Adjust server time
If you have a server in a different timezone to you then you might be seeing funny things happen when you add the time to a MySQL database for example. You can fix this by adding or subtracting hours as in the example below.
$now = date('Y-m-d-G');
$now = strftime("%Y-%m-%d-%H", strtotime("$now -8 hours"));

Create a slug URL from string of text
Here we’re passing in a simple string of text converting it to lowercase and replacing all the spaces with a dash.
function create_slug(strtolower($string)){
   $slug=preg_replace('/[^a-z0-9-]+/', '-', $string);
   return $slug;
echo create_slug('Create a slug URL from string of text');

Convert HEX value to RBG
If you’ve ever need to get an RGB colour format converted from a Hexadecimal this is the function for the job.
function hextorgb($hexvalue){
        if($hexvalue[0] == '#') {
                $hexvalue = substr( $hexvalue, 1);
        if(strlen( $hexvalue ) == 6){
                list($r, $g, $b) = array($hexvalue[0] . $hexvalue[1], $hexvalue[2] . $hexvalue[3], $hexvalue[4] . $hexvalue[5]);
        }elseif (strlen($hexvalue) == 3) {
                list($r,$g,$b) = array($hexvalue[0] . $hexvalue[0], $hexvalue[1] . $hexvalue[1], $hexvalue[2] . $hexvalue[2]);
                return false;
        $r = hexdec($r);
        $g = hexdec($g);
        $b = hexdec($b);
        return array('R' => $r, 'G' => $g, 'B' => $b);
$rgb = hextorgb('#fff000');

Display a users Gravatar image
Getting users images from Gravatar is simple. If you have the users email address you just need to MD5 hash it and append it to the gravatar URL.
$gravatar = 'http://www.gravatar.com/avatar/' . md5($email_address) . '?s=32';
echo '<img src="' . $gravatar . '" width="32" height="32"/>';

Convert links in a string of text to hyperlinks
Very useful function which will convert a string of text and ad hyperlinks to all the URLs. We loop through each URL and add a hyperlink
function url_to_link($text){
            $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
            // Check if there is a url in the string
            if (preg_match_all($reg_exUrl, $text, $url)) {
                foreach($url[0] as $v){
                    $position = strpos($text,' '.$v)+1;   
                    $text = substr_replace($text,'', $position, strlen($v));
                    $text = substr_replace($text,''.$v.'', $position ,0);
                return $text;
            else {
                // if no urls in the text just return the text
                return $text;
$string = 'This is a string of text and we have a link: http://papermashup.com we also have another link http://google.com';
echo url_to_link($string);
Parse JSON in PHP
Parsing a string of JSON is easier than you may think as we can use the json_decode() function in PHP which will convert the JSON into an array in PHP which we can then manipulate as needed.
$json ='{"id":0,"name":"Ashley","surname":"Ford","Website":"http://papermashup.com"} ';
 // print  the array
 echo $array->name;
Как попытаться поточнее определить язык посетителя и перенаправить его в нужную сторону:

	<?php  // List of available localised versions as 'lang code' =--> 'url' map
	$sites = array(
	    "en" => "http://en.mysite.com/",
	    "es" => "http://es.mysite.com/",
	    "fr" => "http://fr.mysite.com/",
	// Get 2 char lang code
	$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
	// Set default language if a '$lang' version of site is not available
	if (!in_array($lang, array_keys($sites))){
	    $lang = 'en';
	// Finally redirect to desired location
	header('Location: ' . $sites[$lang]);

Рейтинг статьи:
Уважаемый посетитель, Вы зашли на сайт как незарегистрированный пользователь. Мы рекомендуем Вам зарегистрироваться либо зайти на сайт под своим именем.