-
Notifications
You must be signed in to change notification settings - Fork 6
/
StringHelper.php
56 lines (53 loc) · 1.8 KB
/
StringHelper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
namespace mgcode\helpers;
class StringHelper extends \yii\helpers\StringHelper
{
/**
* Make a string's first character uppercase
* Works with various encodings
* @param string $str
* @param bool $lowerEnd
* @param string $encoding
* @return string
*/
public static function ucfirst($str, $lowerEnd = false, $encoding = 'UTF-8')
{
$firstLetter = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding);
if ($lowerEnd) {
$strEnd = mb_strtolower(mb_substr($str, 1, mb_strlen($str, $encoding), $encoding), $encoding);
} else {
$strEnd = mb_substr($str, 1, mb_strlen($str, $encoding), $encoding);
}
return $firstLetter.$strEnd;
}
/**
* Generates random string
* @param integer $length Default value 8
* @param bool $allowUppercase Whether to allow uppercase characters
* @return string
*/
public static function generateRandomString($length = 8, $allowUppercase = true)
{
$validCharacters = 'abcdefghijklmnopqrstuxyvwz1234567890';
if ($allowUppercase) {
$validCharacters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
return static::generateRandomStringFromChars($length, $validCharacters);
}
/**
* Generates random string from given characters
* @param integer $length Default value 8
* @param string $validCharacters List with valid characters
* @return string
*/
public static function generateRandomStringFromChars($length, $validCharacters)
{
$validCharNumber = strlen($validCharacters);
$result = '';
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
}