Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Defines string apis
19
 *
20
 * @package    core
21
 * @copyright  (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
defined('MOODLE_INTERNAL') || die();
26
 
27
/**
28
 * defines string api's for manipulating strings
29
 *
30
 * This class is used to manipulate strings under Moodle 1.6 an later. As
31
 * utf-8 text become mandatory a pool of safe functions under this encoding
32
 * become necessary. The name of the methods is exactly the
33
 * same than their PHP originals.
34
 *
35
 * This class was previously based on Typo3 which has now been removed and uses
36
 * native functions now.
37
 *
38
 * @package   core
39
 * @category  string
40
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
41
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42
 */
43
class core_text {
44
    /** @var string Byte order mark for UTF-8 */
45
    const UTF8_BOM = "\xef\xbb\xbf";
46
 
47
    /**
48
     * @var string[] Array of strings representing Unicode non-characters
49
     */
50
    protected static $noncharacters;
51
 
52
    /**
53
     * Check whether the charset is supported by mbstring.
54
     * @param string $charset Normalised charset
55
     * @return bool
56
     */
57
    public static function is_charset_supported(string $charset): bool {
58
        static $cache = null;
59
        if (!$cache) {
60
            $cache = array_flip(array_map('strtolower', mb_list_encodings()));
61
        }
62
 
63
        if (isset($cache[strtolower($charset)])) {
64
            return true;
65
        }
66
 
67
        // We haven't found the charset, check if mb has aliases for the charset.
68
        try {
69
            return mb_encoding_aliases($charset) !== false;
70
        } catch (Throwable $e) {
71
            // A ValueError will be thrown if unsupported.
72
        }
73
 
74
        return false;
75
    }
76
 
77
    /**
78
     * @deprecated since Moodle 4.0. See MDL-53544.
79
     */
1441 ariadna 80
    #[\core\attribute\deprecated(
81
        'core_text::reset_caches',
82
        since: '4.0',
83
        reason:'Typo3 has been removed and caches aren\'t used anymore.',
84
        mdl: 'MDL-53544',
85
        final: true,
86
    )]
87
    public static function reset_caches(): void {
88
        \core\deprecation::emit_deprecation([self::class, __FUNCTION__]);
1 efrain 89
    }
90
 
91
    /**
92
     * Standardise charset name
93
     *
94
     * Please note it does not mean the returned charset is actually supported.
95
     *
96
     * @static
97
     * @param string $charset raw charset name
98
     * @return string normalised lowercase charset name
99
     */
100
    public static function parse_charset($charset) {
101
        $charset = strtolower($charset ?? '');
102
 
103
        if ($charset === 'utf8' or $charset === 'utf-8') {
104
            return 'utf-8';
105
        }
106
 
107
        if (preg_match('/^(cp|win|windows)-?(12[0-9]{2})$/', $charset, $matches)) {
108
            return 'windows-'.$matches[2];
109
        }
110
 
111
        if (preg_match('/^iso-8859-[0-9]+$/', $charset, $matches)) {
112
            return $charset;
113
        }
114
 
115
        if ($charset === 'euc-jp') {
116
            return 'euc-jp';
117
        }
118
        if ($charset === 'iso-2022-jp') {
119
            return 'iso-2022-jp';
120
        }
121
        if ($charset === 'shift-jis' or $charset === 'shift_jis') {
122
            return 'shift_jis';
123
        }
124
        if ($charset === 'gb2312') {
125
            return 'gb2312';
126
        }
127
        if ($charset === 'gb18030') {
128
            return 'gb18030';
129
        }
130
        if ($charset === 'ms-ansi') {
131
            return 'windows-1252';
132
        }
133
 
134
        // We have reached this stage and haven't matched with anything. Return the original.
135
        return $charset;
136
    }
137
 
138
    /**
139
     * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter.
140
     * If both source and target are utf-8 it tries to fix invalid characters only.
141
     *
142
     * @param string $text
143
     * @param string $fromCS source encoding
144
     * @param string $toCS result encoding
145
     * @return string|bool converted string or false on error
146
     */
147
    public static function convert($text, $fromCS, $toCS='utf-8') {
148
        $fromCS = self::parse_charset($fromCS);
149
        $toCS   = self::parse_charset($toCS);
150
 
151
        $text = (string)$text; // we can work only with strings
152
 
153
        if ($text === '') {
154
            return '';
155
        }
156
 
157
        if ($fromCS === 'utf-8') {
158
            $text = fix_utf8($text);
159
            if ($toCS === 'utf-8') {
160
                return $text;
161
            }
162
        }
163
 
164
        if ($toCS === 'ascii') {
165
            // Try to normalize the conversion a bit if the target is ascii.
166
            return self::specialtoascii($text, $fromCS);
167
        }
168
 
169
        // Prevent any error notices, do not use //IGNORE so that we get
170
        // consistent result if iconv fails.
171
        return @iconv($fromCS, $toCS.'//TRANSLIT', $text);
172
    }
173
 
174
    /**
175
     * Multibyte safe substr() function, uses mbstring or iconv
176
     *
177
     * @param string $text string to truncate
178
     * @param int $start negative value means from end
179
     * @param int $len maximum length of characters beginning from start
180
     * @param string $charset encoding of the text
181
     * @return string portion of string specified by the $start and $len
182
     */
183
    public static function substr($text, $start, $len=null, $charset='utf-8') {
184
        $charset = self::parse_charset($charset);
185
 
186
        // Check whether the charset is supported by mbstring. CP1250 is not supported. Fall back to iconv.
187
        if (self::is_charset_supported($charset)) {
188
            $result = mb_substr($text ?? '', $start, $len, $charset);
189
        } else {
190
            $result = (string)iconv_substr($text ?? '', $start, $len, $charset);
191
        }
192
 
193
        return $result;
194
    }
195
 
196
    /**
197
     * Truncates a string to no more than a certain number of bytes in a multi-byte safe manner.
198
     * UTF-8 only!
199
     *
200
     * @param string $string String to truncate
201
     * @param int $bytes Maximum length of bytes in the result
202
     * @return string Portion of string specified by $bytes
203
     * @since Moodle 3.1
204
     */
205
    public static function str_max_bytes($string, $bytes) {
206
        return mb_strcut($string ?? '', 0, $bytes, 'UTF-8');
207
    }
208
 
209
    /**
210
     * Finds the last occurrence of a character in a string within another.
211
     * UTF-8 ONLY safe mb_strrchr().
212
     *
213
     * @param string $haystack The string from which to get the last occurrence of needle.
214
     * @param string $needle The string to find in haystack.
215
     * @param boolean $part If true, returns the portion before needle, else return the portion after (including needle).
216
     * @return string|false False when not found.
217
     * @since Moodle 2.4.6, 2.5.2, 2.6
218
     */
219
    public static function strrchr($haystack, $needle, $part = false) {
220
        if (is_null($haystack)) {
221
            // Compatibility with behavior in PHP before version 8.1.
222
            return false;
223
        }
224
        return mb_strrchr($haystack, $needle, $part, 'UTF-8');
225
    }
226
 
227
    /**
228
     * Multibyte safe strlen() function, uses mbstring or iconv
229
     *
230
     * @param string $text input string
231
     * @param string $charset encoding of the text
232
     * @return int number of characters
233
     */
234
    public static function strlen($text, $charset='utf-8') {
235
        $charset = self::parse_charset($charset);
236
 
237
        if (self::is_charset_supported($charset)) {
238
            return mb_strlen($text ?? '', $charset);
239
        }
240
 
241
        return iconv_strlen($text ?? '', $charset);
242
    }
243
 
244
    /**
245
     * Multibyte safe strtolower() function, uses mbstring.
246
     *
247
     * @param string $text input string
248
     * @param string $charset encoding of the text (may not work for all encodings)
249
     * @return string lower case text
250
     */
251
    public static function strtolower($text, $charset='utf-8') {
252
        $charset = self::parse_charset($charset);
253
 
254
        // Confirm mbstring can handle the charset.
255
        if (self::is_charset_supported($charset)) {
256
            return mb_strtolower($text ?? '', $charset);
257
        }
258
 
259
        // The mbstring extension cannot handle the charset. Convert to UTF-8.
260
        $convertedtext = self::convert($text, $charset, 'utf-8');
261
        $result = mb_strtolower($convertedtext);
262
        $result = self::convert($result, 'utf-8', $charset);
263
        return $result;
264
    }
265
 
266
    /**
267
     * Multibyte safe strtoupper() function, uses mbstring.
268
     *
269
     * @param string $text input string
270
     * @param string $charset encoding of the text (may not work for all encodings)
271
     * @return string upper case text
272
     */
273
    public static function strtoupper($text, $charset='utf-8') {
274
        $charset = self::parse_charset($charset);
275
 
276
        // Confirm mbstring can handle the charset.
277
        if (self::is_charset_supported($charset)) {
278
            return mb_strtoupper($text ?? '', $charset);
279
        }
280
 
281
        // The mbstring extension cannot handle the charset. Convert to UTF-8.
282
        $convertedtext = self::convert($text, $charset, 'utf-8');
283
        $result = mb_strtoupper($convertedtext);
284
        $result = self::convert($result, 'utf-8', $charset);
285
        return $result;
286
    }
287
 
288
    /**
289
     * Find the position of the first occurrence of a substring in a string.
290
     * UTF-8 ONLY safe strpos(), uses mbstring
291
     *
292
     * @param string $haystack the string to search in
293
     * @param string $needle one or more charachters to search for
294
     * @param int $offset offset from begining of string
295
     * @return int the numeric position of the first occurrence of needle in haystack.
296
     */
297
    public static function strpos($haystack, $needle, $offset=0) {
298
        return mb_strpos($haystack ?? '', $needle, $offset, 'UTF-8');
299
    }
300
 
301
    /**
302
     * Find the position of the last occurrence of a substring in a string
303
     * UTF-8 ONLY safe strrpos(), uses mbstring
304
     *
305
     * @param string $haystack the string to search in
306
     * @param string $needle one or more charachters to search for
307
     * @return int the numeric position of the last occurrence of needle in haystack
308
     */
309
    public static function strrpos($haystack, $needle) {
310
        if (is_null($haystack)) {
311
            // Compatibility with behavior in PHP before version 8.1.
312
            return false;
313
        }
314
        return mb_strrpos($haystack, $needle, 0, 'UTF-8');
315
    }
316
 
317
    /**
318
     * Reverse UTF-8 multibytes character sets (used for RTL languages)
319
     * (We only do this because there is no mb_strrev or iconv_strrev)
320
     *
321
     * @param string $str the multibyte string to reverse
322
     * @return string the reversed multi byte string
323
     */
324
    public static function strrev($str) {
325
        preg_match_all('/./us', $str ?? '', $ar);
326
        return join('', array_reverse($ar[0]));
327
    }
328
 
329
    /**
330
     * Try to convert upper unicode characters to plain ascii,
331
     * the returned string may contain unconverted unicode characters.
332
     *
333
     * With the removal of typo3, iconv conversions was found to be the best alternative to Typo3's function.
334
     * However using the standard iconv call
335
     *      iconv($charset, 'ASCII//TRANSLIT//IGNORE', (string) $text);
336
     * resulted in invalid strings with special character from Russian/Japanese. To solve this, the transliterator was
337
     * used but this resulted in empty strings for certain strings in our test. It was decided to use a combo of the 2
338
     * to cover all our bases. Refer MDL-53544 for further information.
339
     *
340
     * @param string $text input string
341
     * @param string $charset encoding of the text
342
     * @return string converted ascii string
343
     */
344
    public static function specialtoascii($text, $charset='utf-8') {
345
        $charset = self::parse_charset($charset);
346
        $oldlevel = error_reporting(E_PARSE);
347
 
348
        // Always convert to utf-8, so transliteration can do its work always.
349
        if ($charset !== 'utf-8') {
350
            $text = iconv($charset, 'utf-8'.'//TRANSLIT', $text);
351
        }
352
        $text = transliterator_transliterate('Any-Latin; Latin-ASCII', (string) $text);
353
 
354
        // Still, apply iconv because some chars are not handled by transliterate.
355
        $result = iconv('utf-8', 'ASCII//TRANSLIT//IGNORE', (string) $text);
356
 
357
        error_reporting($oldlevel);
358
        return $result;
359
    }
360
 
361
    /**
362
     * Generate a correct base64 encoded header to be used in MIME mail messages.
363
     * This function seems to be 100% compliant with RFC1342. Credits go to:
364
     * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
365
     *
366
     * @param string $text input string
367
     * @param string $charset encoding of the text
368
     * @return string base64 encoded header
369
     */
370
    public static function encode_mimeheader($text, $charset='utf-8') {
371
        if (empty($text)) {
372
            return (string)$text;
373
        }
374
        // Normalize charset
375
        $charset = self::parse_charset($charset);
376
        // If the text is pure ASCII, we don't need to encode it
377
        if (self::convert($text, $charset, 'ascii') == $text) {
378
            return $text;
379
        }
380
        // Although RFC says that line feed should be \r\n, it seems that
381
        // some mailers double convert \r, so we are going to use \n alone
382
        $linefeed="\n";
383
        // Define start and end of every chunk
384
        $start = "=?$charset?B?";
385
        $end = "?=";
386
        // Accumulate results
387
        $encoded = '';
388
        // Max line length is 75 (including start and end)
389
        $length = 75 - strlen($start) - strlen($end);
390
        // Multi-byte ratio
391
        $multilength = self::strlen($text, $charset);
392
        // Detect if strlen and friends supported
393
        if ($multilength === false) {
394
            if ($charset == 'GB18030' or $charset == 'gb18030') {
395
                while (strlen($text)) {
396
                    // try to encode first 22 chars - we expect most chars are two bytes long
397
                    if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
398
                        $chunk = $matches[0];
399
                        $encchunk = base64_encode($chunk);
400
                        if (strlen($encchunk) > $length) {
401
                            // find first 11 chars - each char in 4 bytes - worst case scenario
402
                            preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
403
                            $chunk = $matches[0];
404
                            $encchunk = base64_encode($chunk);
405
                        }
406
                        $text = substr($text, strlen($chunk));
407
                        $encoded .= ' '.$start.$encchunk.$end.$linefeed;
408
                    } else {
409
                        break;
410
                    }
411
                }
412
                $encoded = trim($encoded);
413
                return $encoded;
414
            } else {
415
                return false;
416
            }
417
        }
418
        $ratio = $multilength / strlen($text);
419
        // Base64 ratio
420
        $magic = $avglength = floor(3 * $length * $ratio / 4);
421
        // basic infinite loop protection
422
        $maxiterations = strlen($text)*2;
423
        $iteration = 0;
424
        // Iterate over the string in magic chunks
425
        for ($i=0; $i <= $multilength; $i+=$magic) {
426
            if ($iteration++ > $maxiterations) {
427
                return false; // probably infinite loop
428
            }
429
            $magic = $avglength;
430
            $offset = 0;
431
            // Ensure the chunk fits in length, reducing magic if necessary
432
            do {
433
                $magic -= $offset;
434
                $chunk = self::substr($text, $i, $magic, $charset);
435
                $chunk = base64_encode($chunk);
436
                $offset++;
437
            } while (strlen($chunk) > $length);
438
            // This chunk doesn't break any multi-byte char. Use it.
439
            if ($chunk)
440
                $encoded .= ' '.$start.$chunk.$end.$linefeed;
441
        }
442
        // Strip the first space and the last linefeed
443
        $encoded = substr($encoded, 1, -strlen($linefeed));
444
 
445
        return $encoded;
446
    }
447
 
448
    /**
449
     * Returns HTML entity transliteration table.
450
     * @return array with (html entity => utf-8) elements
451
     */
452
    protected static function get_entities_table() {
1441 ariadna 453
        static $translationtable = null;
1 efrain 454
 
455
        // Generate/create $trans_tbl
1441 ariadna 456
        if (!isset($translationtable)) {
457
            $translationtable = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML401, 'UTF-8');
458
            $translationtable = array_flip($translationtable);
1 efrain 459
        }
460
 
1441 ariadna 461
        return $translationtable;
1 efrain 462
    }
463
 
464
    /**
465
     * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
466
     * Original from laurynas dot butkus at gmail at:
467
     * http://php.net/manual/en/function.html-entity-decode.php#75153
468
     * with some custom mods to provide more functionality
469
     *
470
     * @param string $str input string
471
     * @param boolean $htmlent convert also html entities (defaults to true)
472
     * @return string encoded UTF-8 string
473
     */
474
    public static function entities_to_utf8($str, $htmlent=true) {
475
        static $callback1 = null ;
476
        static $callback2 = null ;
477
 
478
        if (!$callback1 or !$callback2) {
479
            $callback1 = function($matches) {
480
                return core_text::code2utf8(hexdec($matches[1]));
481
            };
482
            $callback2 = function($matches) {
483
                return core_text::code2utf8($matches[1]);
484
            };
485
        }
486
 
487
        $result = (string)$str;
488
        $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback1, $result);
489
        $result = preg_replace_callback('/&#([0-9]+);/', $callback2, $result);
490
 
491
        // Replace literal entities (if desired)
492
        if ($htmlent) {
493
            $trans_tbl = self::get_entities_table();
494
            // It should be safe to search for ascii strings and replace them with utf-8 here.
495
            $result = strtr($result, $trans_tbl);
496
        }
497
        // Return utf8-ised string
498
        return $result;
499
    }
500
 
501
    /**
502
     * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
503
     *
504
     * @param string $str input string
505
     * @param boolean $dec output decadic only number entities
506
     * @param boolean $nonnum remove all non-numeric entities
507
     * @return string converted string
508
     */
509
    public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
510
        static $callback = null ;
511
 
512
        if ($nonnum) {
513
            $str = self::entities_to_utf8($str, true);
514
        }
515
 
516
        $result = mb_strtolower(mb_encode_numericentity($str ?? '', [0xa0, 0xffff, 0, 0xffff], 'UTF-8', true));
517
 
518
        // We cannot use the decimal equivalent of the above call due to the unit test and our allowance for
519
        // entities to be entered within the provided $str. Refer to the correspond unit test for examples.
520
        if ($dec) {
521
            if (!$callback) {
522
                $callback = function($matches) {
523
                    return '&#' . hexdec($matches[1]) . ';';
524
                };
525
            }
526
            $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback, $result);
527
        }
528
 
529
        return $result;
530
    }
531
 
532
    /**
533
     * Removes the BOM from unicode string {@link http://unicode.org/faq/utf_bom.html}
534
     *
535
     * @param string $str input string
536
     * @return string
537
     */
538
    public static function trim_utf8_bom($str) {
539
        if (is_null($str)) {
540
            return null;
541
        }
542
        $bom = self::UTF8_BOM;
543
        if (strpos($str, $bom) === 0) {
544
            return substr($str, strlen($bom));
545
        }
546
        return $str;
547
    }
548
 
549
    /**
550
     * There are a number of Unicode non-characters including the byte-order mark (which may appear
551
     * multiple times in a string) and also other ranges. These can cause problems for some
552
     * processing.
553
     *
554
     * This function removes the characters using string replace, so that the rest of the string
555
     * remains unchanged.
556
     *
557
     * @param string $value Input string
558
     * @return string Cleaned string value
559
     * @since Moodle 3.5
560
     */
561
    public static function remove_unicode_non_characters($value) {
562
        // Set up list of all Unicode non-characters for fast replacing.
563
        if (!self::$noncharacters) {
564
            self::$noncharacters = [];
565
            // This list of characters is based on the Unicode standard. It includes the last two
566
            // characters of each code planes 0-16 inclusive...
567
            for ($plane = 0; $plane <= 16; $plane++) {
568
                $base = ($plane === 0 ? '' : dechex($plane));
569
                self::$noncharacters[] = html_entity_decode('&#x' . $base . 'fffe;', ENT_COMPAT);
570
                self::$noncharacters[] = html_entity_decode('&#x' . $base . 'ffff;', ENT_COMPAT);
571
            }
572
            // ...And the character range U+FDD0 to U+FDEF.
573
            for ($char = 0xfdd0; $char <= 0xfdef; $char++) {
574
                self::$noncharacters[] = html_entity_decode('&#x' . dechex($char) . ';', ENT_COMPAT);
575
            }
576
        }
577
 
578
        // Do character replacement.
579
        return str_replace(self::$noncharacters, '', $value);
580
    }
581
 
582
    /**
583
     * Returns encoding options for select boxes, utf-8 and platform encoding first
584
     *
585
     * @return array encodings
586
     */
587
    public static function get_encodings() {
588
        $encodings = array();
589
        $encodings['UTF-8'] = 'UTF-8';
590
        $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
591
        if ($winenc != '') {
592
            $encodings[$winenc] = $winenc;
593
        }
594
        $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
595
        $encodings[$nixenc] = $nixenc;
596
 
597
        $listedencodings = mb_list_encodings();
598
        foreach ($listedencodings as $enc) {
599
            $enc = strtoupper($enc);
600
            $encodings[$enc] = $enc;
601
        }
602
        return $encodings;
603
    }
604
 
605
    /**
606
     * Returns the utf8 string corresponding to the unicode value
607
     * (from php.net, courtesy - romans@void.lv)
608
     *
609
     * @param  int    $num one unicode value
610
     * @return string the UTF-8 char corresponding to the unicode value
611
     */
612
    public static function code2utf8($num) {
613
        if ($num < 128) {
614
            return chr($num);
615
        }
616
        if ($num < 2048) {
617
            return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
618
        }
619
        if ($num < 65536) {
620
            return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
621
        }
622
        if ($num < 2097152) {
623
            return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
624
        }
625
        return '';
626
    }
627
 
628
    /**
629
     * Returns the code of the given UTF-8 character
630
     *
631
     * @param  string $utf8char one UTF-8 character
632
     * @return int    the code of the given character
633
     */
634
    public static function utf8ord($utf8char) {
635
        if ($utf8char == '') {
636
            return 0;
637
        }
638
        $ord0 = ord($utf8char[0]);
639
        if ($ord0 >= 0 && $ord0 <= 127) {
640
            return $ord0;
641
        }
642
        $ord1 = ord($utf8char[1]);
643
        if ($ord0 >= 192 && $ord0 <= 223) {
644
            return ($ord0 - 192) * 64 + ($ord1 - 128);
645
        }
646
        $ord2 = ord($utf8char[2]);
647
        if ($ord0 >= 224 && $ord0 <= 239) {
648
            return ($ord0 - 224) * 4096 + ($ord1 - 128) * 64 + ($ord2 - 128);
649
        }
650
        $ord3 = ord($utf8char[3]);
651
        if ($ord0 >= 240 && $ord0 <= 247) {
652
            return ($ord0 - 240) * 262144 + ($ord1 - 128 )* 4096 + ($ord2 - 128) * 64 + ($ord3 - 128);
653
        }
654
        return false;
655
    }
656
 
657
    /**
658
     * Makes first letter of each word capital - words must be separated by spaces.
659
     * Use with care, this function does not work properly in many locales!!!
660
     *
661
     * @param string $text input string
662
     * @return string
663
     */
664
    public static function strtotitle($text) {
665
        if (empty($text)) {
666
            return $text;
667
        }
668
 
669
        return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
670
    }
1441 ariadna 671
 
672
    /**
673
     * Trims control characters out of a string.
674
     * Example: (\x00-\x1f) and (\x7f)
675
     *
676
     * @param string $text Input string
677
     * @return string Cleaned string value
678
     */
679
    public static function trim_ctrl_chars(string $text): string {
680
        // Remove control characters text.
681
        return preg_replace('/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]/i', '', $text);
682
    }
1 efrain 683
}