Code Snippets

Small useful code fractions in PHP

This is a collection of smaller code snippets in PHP to solve some problems.

Gmail Address Normalization

An email address from Google's Gmail can be transformed in various ways into different looking email addresses while still going to the same account. A Gmail user can do the following to have multiple email addresses:

  • Using a plus address: gmail+test@gmail.com is really gmail@gmail.com
  • Changing the host to googlemail.com; gmail@googlemail.com is gmail@gmail.com
  • Adding additional dots to the name: g.mail@gmail.com still goes to gmail@gmail.com

To see which Gmail email addresses belong to the same account, run them through gmail_id() and verify if any of the results are equal.

function gmail_id($mail) {
  
$mail_part explode('@'strtolower($mail));
  if (
$mail_part[1] !== 'gmail.com' && $mail_part[1] !== 'googlemail.com') {
    return 
$mail;
  }
  
$plus_position strpos($mail_part[0], '+');
  if (
$plus_position !== false) {
    
$mail_part[0] = substr($mail_part[0], 0$plus_position);
  }
  return 
str_replace('.'''$mail_part[0]) . '@gmail.com';
}
Examples of usage:
echo gmail_id('gmail@googlemail.com'); // gmail@gmail.com
echo gmail_id('gm.Ail@gmail.com');     // gmail@gmail.com
echo gmail_id('gmail+test@gmail.com'); // gmail@gmail.com

Other email addresses are returned unmodified.

Note: Do not store the email addresses in this transformed form—it's unexpected to the user to receive mails with a modified address and will cause issues, e.g. for password reset procedures. Additionally, Gmail accounts are registered with whatever dots the user supplied; sending an email to the dot-less version of the address will still work, but Gmail will point this difference out to the user.

Highlight PHP Code

This highlights some PHP code, without the need of the wrapping <?php and ?> tags. (This very function is used on this page.) The result is HTML-compliant.
function highlight_code($text) {
  
$code highlight_string('<?php ' $text '?>'true);
  if (
substr($code862) !== '<s') {
    return 
'<span style="color: #0000BB">' substr($code79, -57);
  }
  return 
substr($code86, -57);
}
Examples:
echo code_highlight('var_dump($_SERVER); $a = 3;');

If you are using PHP 4, you will have to change the numbers 79 and -57 as highlight_string() uses the tag <font> (instead of <span>) prior to PHP 5.

Anonymize IP Addresses

The following is a function that allows you to show parts of an IP address in a partially anonymized form. It will output an IP address like 178.162.87.50 as 178.162.76.xx.
function anonymize_ip($ip) {
  
$last_dot strrpos($ip'.') + 1;
  return 
substr($ip0$last_dot)
    . 
str_repeat('x'strlen($ip) - $last_dot);
}
Examples of usage:
echo anonymize_ip('123.45.67.89'); // "123.45.67.xx"
echo anonymize_ip('12.34.56.123'); // "12.34.56.xxx"
For IPv6 addresses, the following function can be used in the same way. It will replace the last group of the address with x's.
function anonymize_ipv6($ip) {
  
$last_colon strrpos($ip':') + 1;
  return 
substr($ip0$last_colon)
    . 
str_repeat('x'strlen($ip) - $last_colon);
}

Pad IP Addresses

Pads IPv4 addresses with 0's so that all groups of the address have three digits. This is useful for display purposes as all IP addresses will have the same length, e.g. to make entries in logs align.
function pad_ip($ip) {
  return 
implode('.'array_map(function ($entry) {
    return 
str_pad($entry3'0'STR_PAD_LEFT);
  }, 
explode('.'$ip)));
}
Examples:
echo pad_ip('127.0.0.1');   // 127.000.000.001
echo pad_ip('1.234.56.78'); // 001.234.056.078

Round to First Significant Digits

Function to round a number with many decimals to the first few. For example, if you want to display the difference between two timestamps with microsecond precision, you may want to round the number to the first few digits like "0.00037 s" or "0.06 s" rather than showing "0.000374924 s".

By default, the first two non-zero digits are shown after the decimal point, as determined by $added_digits. You can change it to 1 or something else to change how many non-zero digits are shown.
function proper_precision($difference) {
  
$added_digits 2;
  if (
$difference >= || $difference <= -1) {
    return 
$added_digits;
  }
  
preg_match('~.*\.(0*)[^0]~'$difference$matches);
  if (isset(
$matches[1])) {
    return 
strlen($matches[1]) + $added_digits;
  }
  return 
$added_digits;
}

function 
proper_round($difference) {
  return 
round($differenceproper_precision($difference));
}
Examples:
echo proper_round(0.0042345); // 0.0042
echo proper_round(32.9437);   // 32.94
echo proper_round(-0.0369);   // -0.037
echo proper_round(2.00000);   // 2

Ensure That a Parameter is Always Even or Odd

Ensures that a parameter is always odd or even by adding or subtracting 1 to the number when necessary. get_odd() adds 1 to even numbers and get_even() subtracts 1 to odd numbers.

How it works: get_odd() makes sure that the last bit of the number is a 1, since numbers whose binary representation end with 0 are even numbers. Similarly, with a few additional bit flips, get_even() ensures that the last bit of a number is a 0.

function get_odd($n) {
  return 
$n 1;
}
function get_even($n) {
  return ~(~
$n 1);
}
Examples:
echo get_even(17) . ', ' get_odd(17); // 16, 17
echo get_even(-8) . ', ' get_odd(-8); // -8, -7
echo get_even(24.9) . ', ' get_odd(24.9); // 24, 25

If you need to specify whether the functions should add or subtract 1 to make numbers even or odd, you could use the alternate functions provided below (click on link below to show). Both functions below add 1 when a "correction" is needed; replace the + in those functions with a - to make them subtract instead when necessary.

Show/hide alternate functions

Change a Number's Sign

Changing a positive number into a negative and vice versa can be done in one line:
function flip_sign($in) {
  return (
$in);
}
Examples:
echo flip_sign(1.5); // outputs -1.5
echo flip_sign('-2.'); // outputs 2
echo flip_sign(0); // outputs 0

If you are using values which cannot be interpreted as numeric values (e.g. change_pol('abc')), 0 will be returned. Even at an error_reporting level of E_ALL, no error is outputted for any scalar input.

Get File Extension

Detects the file extension from a given string. This function returns the text following the last dot of the file name, so more complicated file extensions such as .tar.gz are only returned as ".gz".
function file_ext($file) {
  
$last_dot strrpos($file'.');
  if (
$last_dot !== false) {
    return 
strtolower(substr($file$last_dot 1));
  }
  return 
'file';
}
Examples:
echo file_ext('test.txt'); // "txt"
echo file_ext('PAGE.HTML'); // "html"
echo file_ext('config'); // "file"