Snippets

  • Splitting a string into quoted and unquoted sections

    <?php
    $str = 'unquoted section "quoted" and unquoted
        "another quoted \"with a subquote\" section" more unquoted';
    preg_match_all('/"(?:\\\\.|[^"])*"|[^"]+/', $str, $m);
    print_r($m);
    ?>
  • Function to readable

    <?php
    $str = 'Some_fugly_FunctionNaming_schemeHere';
    $str = preg_replace('/(?<=[a-z\d])([A-Z])|_([a-zA-Z])/e', '" \xDF"&" $1$2"', $str);
    echo $str;
    ?>
  • Linear to nested array

    <?php
    $a = array('a', 'b', 'c');
    foreach (array_reverse($a) as $v) {
        $b = isset($b) ? array($v => $b) : array($v);
    }
    print_r($b);
    ?>
  • Removing duplicate characters

    <?php
    $str = 'foobarrrr';
    $str = preg_replace('/(.)\1+/s', '$1', $str);
    echo $str; // fobar
    ?>
  • Random string

    <?php
     
    /**
     * Generates a random string.
     *
     * @param    int    $length
     *   The length of the string
     * @param    string $ranges
     *   The characters to use, formatted like a regex character class (a-fA-F0-9)
     * @param    bool   $unique
     *   Every character in the result is unique or not
     * @return   string
     *   The resulting string.
     */
    require_once('preg_expand.php');
    function random_string($length = 6, $ranges = 'a-zA-Z0-9', $unique = false) {
        $out = '';
        $chars = preg_expand($ranges, 0);
        if ($unique) {
            $keys = array_rand($chars, $length);
        } else {
            for ($i = $length; $i--;) {
                $keys[] = array_rand($chars);
            }
        }
        foreach ($keys as $k) {
            $out .= $chars[$k];
        }
        return $out;
    }
     
    /**
     * Quick and simple version
     */
    function random_string_simple($length = 6) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        for ($i = $length, $out = ''; $i--;) {
            $out .= $chars{rand(0, 61)};
        }
        return $out;
    }
     
    ?>
  • preg_expand

    <?php
     
    /**
     * Expands all characters from the given PCRE character class definition. 
     *
     * @param    string    $in
     *   The input character class (not contained in '[]')
     * @param    bool      $string
     *   Set to true to return the result as a string
     * @param    int       $begin
     *   The start of the character range to consider
     * @param    int       $end
     *   The end of the character range to consider
     * @return   mixed
     *   All the characters specified by the input. This is a string if the $string
     *   argument has been provided, or else an array with one element per character.
     */
    function preg_expand($in, $string = true, $begin = 0, $end = 127)
    {
        if (!is_string($in) || !($len = strlen($in))) {
            return false;
        }
        $range = range(chr($begin), chr($end));
        $in = strtr($in, array('[' => '\[', ']' => '\]', '/' => '\/'));
        $in = ($in{0} == '^' ? substr($in, 1) : '^' . $in);
        $in = preg_replace('/[' .$in . ']/', '', implode($range));
        return $string ? $in : str_split($in);
    }
     
    ?>
  • secondsh

    <?php
    /**
     * Turns a number of seconds into a human readable time.
     * This function is NOT calendar aware, months and years are based on the
     * average days per year in the Gregorian calendar.
     *
     * @param  int    $in
     *   the input number of seconds
     * @return string
     *   a string representation of the input, broken down into larger units
     */
    function secondsh($in, $limit = 0, $sep = ', ')
    {
        $units = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
        $factors = array(1, 60, 3600, 86400, 604800, 2629746, 31556952);
        for ($i = 7, $bal = 0; $i--;) {
            $cur = floor(($in - $bal) / $factors[$i]);
            if (!$cur && ($i || $in)) {
                continue;
            }
            $bal += $cur * $factors[$i];
            $ret[] = $cur . ' ' . $units[$i] . ($cur != 1 ? 's' : '');
        }
        if ($limit) {
            $ret = array_slice($ret, 0, $limit);
        }
        return implode($sep, $ret);
    }
     
    ?>
  • http_file_exists

    <?php
     
    /**
     * HTTP version of file_exists
     *
     * @param   string  $path   the path to test
     * @param   bool    $redir  accept redirects (3xx) 
     * @return  bool    true if the file exists, false otherwise
     */
    function http_file_exists($path, $redir = false) {
        $path = parse_url($path);
        if (!isset($path['host'])) {
            return false;
        }
        $fp = fsockopen($path['host'], 80, $errno, $errstr, 4);
        if (!$fp) {
            return false;
        }
        if (!isset($path['path'])) {
            $path['path'] = '/';
        }
        $request = "HEAD $path[path] HTTP/1.0\r\n" .
            "Host: $path[host]\r\n" .
            "Connection: close\r\n\r\n";
        fputs($fp, $request);
        $pattern = '#HTTP/[\d\.]+ ' . ($redir ? '[23]' : '2') . '#';
        while (!feof($fp)) {
            $response = fgets($fp, 1024);
            if (preg_match($pattern, $response)) {
                return true;
            }
        }
        fclose($fp);
        return false;
    }
     
    ?>
  • ordinal

    <?php
     
    /**
     * Returns the given integer with an ordinal suffix
     *
     * @param    int    $n
     *   The input integer
     * @return   string
     *   The input and the appropriate ordinal suffix
     * @author
     *   Arpad Ray
     * @version
     *   2005/8/6
     */
    function ordinal($n)
    {
        $ln = (int)substr($n, -1);
        $sln = (int)substr($n, -2);
        $r = array('st','nd','rd');
        $es = (($sln < 11 || $sln > 19) && $ln > 0 && $ln < 4);
        return $n . ($es ? $r[$ln - 1] : 'th');
    }
     
    ?>
  • ucsentences

    <?php
    function ucsentences($str)
    {
        return preg_replace_callback('/([^a-z]*)([a-z])(.*?(?:[.:!?]|\Z))/si', 'ucsentences_callback', $str);
    }
     
    function ucsentences_callback($m)
    {
        return $m[1] . strtoupper($m[2]) . $m[3];
    }
     
    $s = 'the foo, the bar and the baz. something like: what? what! never mind';
    echo ucsentences($s);
    // The foo, the bar and the baz. Something like: What? What! Never mind
     
    ?>