Regular expression examples

Categorías: 

Etiquetas: 

  • Postal code
  • DNI/NIF validation
  • Email
  • Hour:minute:second
  • Replace strings in SQL query
  • Search breakline

Postal code

This will check european postal code (eg: 28008) and US postal code (eg: 12005-1234)

if (preg_match('/^\d{5}(-\d{4})?$/', $postalCode)) {
    // valid postal code
} else {
    // invalid postal code
}

DNI/NIF validation

PHP

/**
 * Checks valid dni/nif and returns true|false 
 * @param string $nif
 * @return boolean
 */
function validateNif($nif)
{
    $nif_codes = 'TRWAGMYFPDXBNJZSQVHLCKE';
 
    $sum = (string) $this->getCifSum($nif);
    $n = 10 - substr($sum, -1);
 
    if (preg_match('/^[0-9]{8}[A-Z]{1}$/', $nif)) {
        // DNIs
        $num = substr($nif, 0, 8);
        return ($nif[8] == $nif_codes[$num % 23]);
    } elseif (preg_match('/^[XYZ][0-9]{7}[A-Z]{1}$/', $nif)) {
        // standar NIEs 
        $tmp = substr($nif, 1, 7);
        $tmp = strtr(substr($nif, 0, 1), 'XYZ', '012') . $tmp;
 
        return ($nif[8] == $nif_codes[$tmp % 23]);
    } elseif (preg_match('/^[KLM]{1}/', $nif)) {
        // special NIFs
        return ($nif[8] == chr($n + 64));
    } elseif (preg_match('/^[T]{1}[A-Z0-9]{8}$/', $nif)) {
        // strange NIE 
        return true;
    }
 
    return false;
}
 
/**
 * 
 * @param string $cif
 * @return string
 */
function getCifSum($cif)
{
    $sum = $cif[2] + $cif[4] + $cif[6];
 
    for ($i = 1; $i < 8; $i += 2) {
        $tmp = (string) (2 * $cif[$i]);
 
        $tmp = $tmp[0] + ((strlen($tmp) == 2) ? $tmp[1] : 0);
 
        $sum += $tmp;
    }
 
    return $sum;
}

Javascript (simple)

/**
* Validate DNI
* @param {String} dni
* @returns {Boolean}
*/
function validateDNI(dni)
{
    var number;
    var let;
    var nif_codes = 'TRWAGMYFPDXBNJZSQVHLCKET';
    var regular_expresion_dni = /^\d{8}[a-zA-Z]$/;
    if (regular_expresion_dni.test(dni) === true) {
        number = dni.substr(0,dni.length-1);
        let = dni.substr(dni.length-1,1);
        number = number % 23;
        nif_codes = nif_codes.substring(number, (number + 1));
        if (nif_codes !== let) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

Email

Javascript

function isValidEmail(email) { 
    var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return regex.test(email);
} 

PHP

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email);
}

Hour:minute:second

/**
 * Checks valid hour:minute or hour:minute:second
 * @param string $hour 
 * @param string $format [optional] H:i | H:i:s
 * @return boolean
 */
function isValidHour($hour, $format = 'H:i')
{
    $isValidHour = false;
 
    switch ($format) {
        case 'H:i':
            if (preg_match("/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/", $hour)) {
                $isValidHour = true;
            }
            break;
 
        case 'H:i:s':
            if (preg_match("/^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/", $hour)) {
                $isValidHour = true;
            }
            break;
    }
 
    return $isValidHour;
}

Replace strings in SQL query

// replace SELECT params to count(*)
$sql = preg_replace('/SELECT (.*) FROM/i', 'SELECT COUNT(*) AS total FROM', $sql);
 
// unset ORDER
$sql = preg_replace('/ORDER BY (.*)/i', '', $sql);

Search breakline

$replace = preg_replace('/<\?[\r\n]/', '<?php', $string);