-
Notifications
You must be signed in to change notification settings - Fork 0
/
utility.php
64 lines (59 loc) · 1.65 KB
/
utility.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
57
58
59
60
61
62
63
64
<?php
/**
* utility functions
* by fliegwerk
* (c) 2020. MIT License
*/
/**
* Removes all non ascii and html compatible characters and replace them with an underscore.
*
* @param string $str the input string
* @return string the replaced string
*/
function remove_non_ascii(string $str): string {
return preg_replace("/[^a-zA-Z0-9-._]/", "_", $str);
}
/**
* Generates an element id that is compatible with the html attribute `id`.
*
* @param string $str the source string
* @return string the generated id
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
*/
function gen_id(string $str): string {
$id = strtolower(remove_non_ascii(trim($str)));
// compatibility
return preg_match("/[^a-z]/", $id[0]) ? substr_replace($id, "_", 0, 1) : $id;
}
/**
* Converts a string to a valid html hexadecimal color.
*
* @param string $color the string with the hex color
* @return string a valid hexadecimal color
*/
function parse_html_color(string $color): string {
if (preg_match('/^#?(?:[0-9a-fA-F]{3}){1,2}$/', $color)) {
if ($color[0] !== '#') return '#' . $color;
return $color;
}
throw new Exception("Color has invalid format: " . $color);
}
/**
* Generates the one character initials from a string.
*
* @param string $str the string to get the initials from
* @return string the initials from the string
*/
function get_initials(string $str): string {
return strtoupper($str[0]) ?? "_";
}
/**
* Returns the filename of a path.
*
* @param string $path the path to cut down
* @return string the filename of file specified by the path
*/
function get_filename(string $path): string {
return pathinfo($path)["filename"];
}