str.php 2.41 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
<?php namespace System;

class Str {

	/**
	 * Convert HTML characters to entities.
	 *
	 * @param  string  $value
	 * @return string
	 */
	public static function entities($value)
	{
13
        return htmlentities($value, ENT_QUOTES, Config::get('application.encoding'), false);
14 15 16 17 18 19 20 21 22 23
	}

    /**
     * Convert a string to lowercase.
     *
     * @param  string  $value
     * @return string
     */
    public static function lower($value)
    {
24
        return function_exists('mb_strtolower') ? mb_strtolower($value, Config::get('application.encoding')) : strtolower($value);
25 26 27 28 29 30 31 32 33 34
    }

    /**
     * Convert a string to uppercase.
     *
     * @param  string  $value
     * @return string
     */
    public static function upper($value)
    {
35
        return function_exists('mb_strtoupper') ? mb_strtoupper($value, Config::get('application.encoding')) : strtoupper($value);
36 37 38 39 40 41 42 43 44 45
    }

    /**
     * Convert a string to title case (ucwords).
     *
     * @param  string  $value
     * @return string
     */
    public static function title($value)
    {
46
        return (function_exists('mb_convert_case')) ? mb_convert_case($value, MB_CASE_TITLE, Config::get('application.encoding')) : ucwords(strtolower($value));
47 48 49
    }

    /**
50 51 52 53 54 55 56 57 58 59 60
     * Get the length of a string.
     *
     * @param  string  $value
     * @return int
     */
    public static function length($value)
    {
        return function_exists('mb_strlen') ? mb_strlen($value, Config::get('application.encoding')) : strlen($value);
    }

    /**
61 62
     * Generate a random alpha or alpha-numeric string.
     *
63
     * Supported types: 'alpha_num' and 'alpha'.
64 65
     *
     * @param  int     $length
66
     * @param  string  $type
67 68
     * @return string
     */
69
    public static function random($length = 16, $type = 'alpha_num')
70 71 72
    {
        $value = '';

Taylor Otwell committed
73
        $pool_length = strlen($pool = static::pool($type)) - 1;
74

75 76
        for ($i = 0; $i < $length; $i++)
        {
77
            $value .= $pool[mt_rand(0, $pool_length)];
78 79 80 81 82
        }

        return $value;
    }

Taylor Otwell committed
83 84 85 86 87 88
    /**
     * Get a chracter pool.
     *
     * @param  string  $type
     * @return string
     */
89
    private static function pool($type = 'alpha_num')
Taylor Otwell committed
90
    {
91
        switch ($type)
Taylor Otwell committed
92
        {
93
            case 'alpha_num':
94 95 96 97
                return '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            
            default:
                return 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Taylor Otwell committed
98 99 100
        }
    }

101
}