1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ElegantMedia\PHPToolkit; |
4
|
|
|
|
5
|
|
|
class Text |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Get a block of text and split it into lines. |
9
|
|
|
* |
10
|
|
|
* @param $text |
11
|
|
|
* @param null $delimiters |
|
|
|
|
12
|
|
|
* |
13
|
|
|
* @return array |
14
|
|
|
* |
15
|
|
|
* @example |
16
|
|
|
* one, two, three |
17
|
|
|
* four |
18
|
|
|
* five |
19
|
|
|
* |
20
|
|
|
* Returns |
21
|
|
|
* ['one', 'two', 'three', 'four', 'five'] |
22
|
|
|
*/ |
23
|
|
|
public static function textToArray($text, $delimiters = null): array |
24
|
|
|
{ |
25
|
|
|
if (!$delimiters) { |
|
|
|
|
26
|
3 |
|
$delimiters = ["\n", ';', ',']; |
27
|
|
|
} |
28
|
3 |
|
|
29
|
3 |
|
// Normalize all line endings to \n |
30
|
|
|
$text = str_replace(["\r\n", "\r"], "\n", $text); |
31
|
|
|
|
32
|
3 |
|
$lines = str_replace($delimiters, $delimiters[0], $text); |
33
|
|
|
$trimmedLines = array_map('trim', explode("\n", $lines)); |
34
|
3 |
|
|
35
|
|
|
// remove empty values |
36
|
|
|
$lines = array_filter($trimmedLines, function ($item) { |
37
|
1 |
|
return $item !== ''; |
38
|
3 |
|
}); |
39
|
3 |
|
|
40
|
|
|
return $lines; |
41
|
3 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Convert an 'existing_snake_case' to 'existing snake case'. |
45
|
|
|
* |
46
|
|
|
* @param $string |
47
|
|
|
* |
48
|
|
|
* @return string |
49
|
|
|
*/ |
50
|
3 |
|
public static function reverseSnake($string) |
51
|
|
|
{ |
52
|
3 |
|
$string = str_replace('_', ' ', $string); |
53
|
|
|
|
54
|
3 |
|
return $string; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Generate a random string without any ambiguous characters. |
59
|
|
|
* |
60
|
|
|
* @param int $length |
61
|
|
|
* |
62
|
3 |
|
* @return string |
63
|
|
|
*/ |
64
|
3 |
|
public static function randomUnambiguous($length = 16): string |
65
|
|
|
{ |
66
|
3 |
|
$pool = '23456789abcdefghkmnpqrstuvwxyz'; |
67
|
|
|
|
68
|
|
|
return substr(str_shuffle(str_repeat($pool, 5)), 0, $length); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|