| 1: | <?php |
| 2: | namespace TIC\CoreBundle\Util; |
| 3: | |
| 4: | |
| 5: | |
| 6: | |
| 7: | class StringHelper |
| 8: | { |
| 9: | |
| 10: | |
| 11: | |
| 12: | |
| 13: | private function __construct() |
| 14: | { |
| 15: | } |
| 16: | |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | |
| 23: | public static function asciify(string $text): string |
| 24: | { |
| 25: | return \preg_replace_callback('/([\xA0-\xFF])/', function($m){ |
| 26: | |
| 27: | $mapA0FF = ' !cL*Y|$_ca<--R_o+23\'mp.,10>423?AAAAAAACEEEEIIIIDNOOOOOx0UUUUYPBaaaaaaaceeeeiiiidnooooo:0uuuuypy'; |
| 28: | return \substr($mapA0FF, \ord($m[0]) - 160, 1); |
| 29: | }, |
| 30: | |
| 31: | \mb_convert_encoding($text, 'iso-8859-15', 'UTF-8') |
| 32: | ); |
| 33: | } |
| 34: | |
| 35: | |
| 36: | |
| 37: | |
| 38: | |
| 39: | |
| 40: | |
| 41: | |
| 42: | |
| 43: | public static function slugify(string $text, string $subst = '-', string $re_ok = 'a-z0-9_\-\.'): string |
| 44: | { |
| 45: | |
| 46: | $slug = self::asciify($text); |
| 47: | |
| 48: | |
| 49: | $slug = \preg_replace('/[^'.$re_ok.']/', '-', \strtolower(\strtr($slug, ' ', '_'))); |
| 50: | |
| 51: | |
| 52: | return \trim(\preg_replace('/([_\-\.])[_\-\.]+/', '$1', $slug), '_-.'); |
| 53: | } |
| 54: | |
| 55: | |
| 56: | |
| 57: | |
| 58: | |
| 59: | |
| 60: | |
| 61: | |
| 62: | public static function jsescape(string $text): string |
| 63: | { |
| 64: | return \preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', function ($matches) { |
| 65: | $char = $matches[0]; |
| 66: | |
| 67: | |
| 68: | |
| 69: | |
| 70: | $shortMap = [ |
| 71: | "\\" => "\\\\", |
| 72: | '/' => '\\/', |
| 73: | "\x08" => '\b', |
| 74: | "\x0C" => '\f', |
| 75: | "\x0A" => '\n', |
| 76: | "\x0D" => '\r', |
| 77: | "\x09" => '\t', |
| 78: | ]; |
| 79: | if (isset($shortMap[$char])) return $shortMap[$char]; |
| 80: | |
| 81: | $codepoint = \mb_ord($char); |
| 82: | if (0x10000 > $codepoint) return \sprintf('\u%04X', $codepoint); |
| 83: | |
| 84: | |
| 85: | |
| 86: | $u = $codepoint - 0x10000; |
| 87: | return \sprintf('\u%04X\u%04X', 0xD800 | ($u >> 10), 0xDC00 | ($u & 0x3FF)); |
| 88: | }, $text); |
| 89: | } |
| 90: | |
| 91: | |
| 92: | |
| 93: | |
| 94: | |
| 95: | |
| 96: | |
| 97: | |
| 98: | |
| 99: | |
| 100: | |
| 101: | public static function genrandom(int $length = 8, mixed $sigils = null): string |
| 102: | { |
| 103: | if (null === $sigils) $sigils = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; |
| 104: | elseif (true === $sigils) $sigils = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-+/*=.,;:!?@#%~(){}[]'; |
| 105: | elseif (false === $sigils) $sigils = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; |
| 106: | |
| 107: | \srand((double)\microtime()*1000000); |
| 108: | $str = ''; |
| 109: | while ($length-- > 0) $str.= $sigils[ \rand() % \strlen($sigils) ]; |
| 110: | return $str; |
| 111: | } |
| 112: | |
| 113: | } |
| 114: | |