1
|
|
|
<?php |
2
|
|
|
namespace Bedd\Common; |
3
|
|
|
|
4
|
|
|
use Bedd\Common\Traits\StaticClassTrait; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* StringUtils |
8
|
|
|
*/ |
9
|
|
|
class StringUtils |
10
|
|
|
{ |
11
|
|
|
use StaticClassTrait; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Split a string on every UpperCase letter |
15
|
|
|
* |
16
|
|
|
* @param string $string |
17
|
|
|
* @throws \InvalidArgumentException |
18
|
|
|
* @return array |
19
|
|
|
*/ |
20
|
|
|
public static function splitOnUpperCase($string) |
21
|
|
|
{ |
22
|
|
|
if (!is_string($string)) { |
23
|
|
|
throw new \InvalidArgumentException('$string should be a string. '.gettype($string).' is given'); |
24
|
|
|
} |
25
|
|
|
return preg_split('/(?=[A-Z])/', $string, -1, PREG_SPLIT_NO_EMPTY); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Split a string on every LowerCase letter |
30
|
|
|
* |
31
|
|
|
* @param string $string |
32
|
|
|
* @throws \InvalidArgumentException |
33
|
|
|
* @return array |
34
|
|
|
*/ |
35
|
|
|
public static function splitOnLowerCase($string) |
36
|
|
|
{ |
37
|
|
|
if (!is_string($string)) { |
38
|
|
|
throw new \InvalidArgumentException('$string should be a string. '.gettype($string).' is given'); |
39
|
|
|
} |
40
|
|
|
return preg_split('/(?=[a-z])/', $string, -1, PREG_SPLIT_NO_EMPTY); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* check if $string starts with $query |
45
|
|
|
* |
46
|
|
|
* @param string $string |
47
|
|
|
* @param string $query |
48
|
|
|
* @return boolean |
49
|
|
|
*/ |
50
|
|
|
public static function startsWith($string, $query) |
51
|
|
|
{ |
52
|
|
|
return $query === '' || substr($string, 0, strlen($query)) === $query; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* check if $string ends with $query |
57
|
|
|
* |
58
|
|
|
* @param string $string |
59
|
|
|
* @param string $query |
60
|
|
|
* @return boolean |
61
|
|
|
*/ |
62
|
|
|
public static function endsWith($string, $query) |
63
|
|
|
{ |
64
|
|
|
return $query === '' || substr($string, -strlen($query)) === $query; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Converts $string into a bool. Supports english and german words |
69
|
|
|
* |
70
|
|
|
* @param string $string |
71
|
|
|
* @param bool $default |
72
|
|
|
* @return boolean |
73
|
|
|
*/ |
74
|
|
|
public static function convertToBool($string, $default = false) |
75
|
|
|
{ |
76
|
|
|
$return = $default; |
77
|
|
|
$yes = ['true', 't', 'yes', 'y', 'ja', 'j', '1']; |
78
|
|
|
$no = ['false', 'f', 'no', 'n', 'nein', '0']; |
79
|
|
|
if (is_scalar($string)) { |
80
|
|
|
$string = strtolower((string) $string); |
81
|
|
|
if (in_array($string, $yes)) { |
82
|
|
|
$return = true; |
83
|
|
|
} else if(in_array($string, $no)) { |
|
|
|
|
84
|
|
|
$return = false; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
return (bool) $return; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|