raunak-gupta
10/11/2016 - 8:03 AM

Very usefully php function for web development.

Very usefully php function for web development.

<?php

if (!function_exists('isValidateDate')) {

    /**
     * Validate Date (i/p format YYYY-MM-DD)
     * ------------------------------------------------
     * '2013-13-01' - false
     * '20132-13-01' - false
     * '2013-11-32' - false
     * '2013-12-01' - true
     * '1970-12-01' - true
     * '2012-02-29' - true
     * 
     * @param  string $date String that need to be checked
     * @param string $format Date format 'Y-m-d' or 'm-d-Y'
     * @return boolean
     */
    function isValidateDate($date, $format = 'Y-m-d') {
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) === $date;
    }

}

if (!function_exists('formatNumber')) {

    function formatNumber($num, $decimal_places = 2) {
        $formattedStr = number_format($num, $decimal_places);
        return $formattedStr;
    }

}

if (!function_exists('isHexcolor')) {

    /**
     * Checks if value is valid hexadecimal color code.
     *
     * @param  mixed  $value Color code of 3-6 digits
     * @return boolean
     */
    function isHexcolor($value) {
        $pattern = '/^#?[a-fA-F0-9]{3,6}$/';
        return (boolean) preg_match($pattern, $value);
    }

}

if (!function_exists('isCreditcard')) {

    /**
     * Checks if value is valid creditcard number.
     *
     * @param  mixed  $value
     * @return boolean
     */
    function isCreditcard($value) {
        $length = strlen($value);
        if ($length < 13 || $length > 19) {
            return false;
        }
        $sum = 0;
        $weight = 2;
        for ($i = $length - 2; $i >= 0; $i--) {
            $digit = $weight * $value[$i];
            $sum += floor($digit / 10) + $digit % 10;
            $weight = $weight % 2 + 1;
        }
        $mod = (10 - $sum % 10) % 10;
        return ($mod == $value[$length - 1]);
    }

}


if (!function_exists('str_replace_limit')) {

    /**
     * Replace a specific word/string for 'n' Number of time.
     *
     * @param  mixed $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
     * @param mixed $replace The replacement value that replaces found <i>search</i> values.
     * @param mixed $subject The string or array being searched and replaced on, otherwise known as the haystack.
     * @return mixed This function returns a string or an array with the replaced values.
     */
    function str_replace_limit($search, $replace, $subject, $limt = 1) {
        $search = '/' . preg_quote($search, '/') . '/';
        return preg_replace($search, $replace, $subject, $limt);
    }

}


if (!function_exists('randomString')) {

    /**
     * Generates a random (~unique) string with a specific lenght (Max 32 Char)
     * ------------------------------------------------
     * 
     * @param  int $length
     * @return String $string
     */
    function randomString($length) {
        return substr(MD5(microtime(true)), 0, $length);
    }

}


if (!function_exists('storeCsvFile')) {

    /**
     * CSV Export (SAVE)
     * ------------------------------------------------
     * 
     * 
     * @param  string $filename File Name
     * @param array $dataArray Array of data set
     * @param string $path Path where file needs to be store ex. storage_path($this->excel_dir)
     * @return file
     */
    function storeCsvFile($filename, $dataArray, $path) {
        $commonFileName = $filename . '.csv';

        $file = fopen($path . $commonFileName, "w"); //Open the CSV file for writting
        foreach ($dataArray as $value) {
            fputcsv($file, explode("\r", implode("\r", $value)));
        }
        fclose($file);

        return $commonFileName;
    }

}

if (!function_exists('pr')) {

    function pr($param = [], $continue = true, $label = NULL) {
        if (!empty($label)) {
            echo '<p>-- ' . $label . ' --</p>';
        }

        echo '<pre>';
        print_r($param);
        echo '</pre><br />';

        if (!$continue) {
            die('-- code execution discontinued --');
        }
    }

}

if (!function_exists('shortenText')) {

    /**
     * Shorten any text to a Specific length, including full last word
     *
     * @param  string $text Text that needs to be shorten
     * @param int $length Character count.
     * @return string.
     */
    function shortenText($text, $length = 140) {
        //beak into 140 character chunks
        $strParts = str_split($text, $length);

        //if the first character of the second chunk is not whitespace
        if (isset($strParts[1]) && !preg_match('/^\s/', $strParts[1])) {
            //strip off the last partial word from the first chunk
            $strParts[0] = preg_replace('/\s\w+$/', '', $strParts[0]);
        }

        //you're done
        $str = $strParts[0];

        return $str . '...';
    }

}