-
Notifications
You must be signed in to change notification settings - Fork 0
/
transliteratorPlus.php
85 lines (64 loc) · 1.84 KB
/
transliteratorPlus.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
class transliteratorPlus {
// allow punctuation in output string
private $punctuation = false;
// make output string to lower
private $toLower = false;
// you can use '-' for url links, ' ' (empty space char) for another use, etc.
// delimiter is not limited by count of characters
private $delimiter = ' ';
/**
* Set punctuation in output string
*
* @param bool $boolean
* @return $this
*/
public function punctuation(bool $boolean): transliteratorPlus {
$this->punctuation = $boolean;
return $this;
}
/**
* Set if output string to be lower-case or original
*
* @param bool $boolean
* @return $this
*/
public function toLower(bool $boolean): transliteratorPlus {
$this->toLower = $boolean;
return $this;
}
/**
* Sets delimiter in output string
*
* @param string $delimiter
* @return $this
*/
public function setDelimiter(string $delimiter): transliteratorPlus {
$this->delimiter = $delimiter;
return $this;
}
/**
* Converts text from Extended Latin to Basic Latin.
*
* @param string $text
* @return string
*/
public function getOutput(string $text): string {
// replace all characters from Extended Latin to Basic Latin
$ret = transliterator_transliterate('Any-Latin; Latin-ASCII', $text);
// remove all non-Latin characters from string and replace them with delimiter
$pattern = '/[^[:alnum:]]+/';
if ($this->punctuation) {
$pattern = '/[^[:alnum:][^[:punct:]]+/';
}
$ret = preg_replace($pattern, $this->delimiter, $ret);
// remove white space from begin and end
$ret = trim($ret);
// make output string lower case
if ($this->toLower) {
$ret = strtolower($ret);
}
// return converted string
return (string)preg_replace(["/" . $this->delimiter . "+/", "/" . $this->delimiter . "+$/", "/^" . $this->delimiter . "+/"], [$this->delimiter, "", ""], $ret);
}
}