BaseStringHelper   F
last analyzed

Complexity

Total Complexity 73

Size/Duplication

Total Lines 539
Duplicated Lines 0 %

Test Coverage

Coverage 99.48%

Importance

Changes 4
Bugs 0 Features 1
Metric Value
eloc 169
dl 0
loc 539
ccs 190
cts 191
cp 0.9948
rs 2.56
c 4
b 0
f 1
wmc 73

20 Methods

Rating   Name   Duplication   Size   Complexity  
A findBetween() 0 16 3
A mb_ucwords() 0 17 4
A base64UrlDecode() 0 3 1
A mask() 0 14 3
A endsWith() 0 21 5
C truncateHtml() 0 50 15
A floatToString() 0 5 1
A byteSubstr() 0 7 2
A startsWith() 0 16 4
A truncate() 0 16 5
A mb_ucfirst() 0 6 1
A normalizeNumber() 0 12 4
A base64UrlEncode() 0 3 1
A truncateWords() 0 12 3
A byteLength() 0 3 1
A countWords() 0 3 1
A basename() 0 16 4
A explode() 0 21 5
A dirname() 0 13 2
B matchWildcard() 0 37 8

How to fix   Complexity   

Complex Class

Complex classes like BaseStringHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BaseStringHelper, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\helpers;
10
11
use Yii;
12
13
/**
14
 * BaseStringHelper provides concrete implementation for [[StringHelper]].
15
 *
16
 * Do not use BaseStringHelper. Use [[StringHelper]] instead.
17
 *
18
 * @author Qiang Xue <[email protected]>
19
 * @author Alex Makarov <[email protected]>
20
 * @since 2.0
21
 */
22
class BaseStringHelper
23
{
24
    /**
25
     * Returns the number of bytes in the given string.
26
     * This method ensures the string is treated as a byte array by using `mb_strlen()`.
27
     *
28
     * @param string $string the string being measured for length
29
     * @return int the number of bytes in the given string.
30
     */
31 424
    public static function byteLength($string)
32
    {
33 424
        return mb_strlen((string)$string, '8bit');
34
    }
35
36
    /**
37
     * Returns the portion of string specified by the start and length parameters.
38
     * This method ensures the string is treated as a byte array by using `mb_substr()`.
39
     *
40
     * @param string $string the input string. Must be one character or longer.
41
     * @param int $start the starting position
42
     * @param int|null $length the desired portion length. If not specified or `null`, there will be
43
     * no limit on length i.e. the output will be until the end of the string.
44
     * @return string the extracted part of string, or FALSE on failure or an empty string.
45
     * @see https://www.php.net/manual/en/function.substr.php
46
     */
47 154
    public static function byteSubstr($string, $start, $length = null)
48
    {
49 154
        if ($length === null) {
50 47
            $length = static::byteLength($string);
51
        }
52
53 154
        return mb_substr((string)$string, $start, $length, '8bit');
54
    }
55
56
    /**
57
     * Returns the trailing name component of a path.
58
     * This method is similar to the php function `basename()` except that it will
59
     * treat both \ and / as directory separators, independent of the operating system.
60
     * This method was mainly created to work on php namespaces. When working with real
61
     * file paths, php's `basename()` should work fine for you.
62
     * Note: this method is not aware of the actual filesystem, or path components such as "..".
63
     *
64
     * @param string $path A path string.
65
     * @param string $suffix If the name component ends in suffix this will also be cut off.
66
     * @return string the trailing name component of the given path.
67
     * @see https://www.php.net/manual/en/function.basename.php
68
     */
69 23
    public static function basename($path, $suffix = '')
70
    {
71 23
        $path = (string)$path;
72
73 23
        $len = mb_strlen($suffix);
74 23
        if ($len > 0 && mb_substr($path, -$len) === $suffix) {
75 1
            $path = mb_substr($path, 0, -$len);
76
        }
77
78 23
        $path = rtrim(str_replace('\\', '/', $path), '/');
79 23
        $pos = mb_strrpos($path, '/');
80 23
        if ($pos !== false) {
81 23
            return mb_substr($path, $pos + 1);
82
        }
83
84 1
        return $path;
85
    }
86
87
    /**
88
     * Returns parent directory's path.
89
     * This method is similar to `dirname()` except that it will treat
90
     * both \ and / as directory separators, independent of the operating system.
91
     *
92
     * @param string $path A path string.
93
     * @return string the parent directory's path.
94
     * @see https://www.php.net/manual/en/function.basename.php
95
     */
96 11
    public static function dirname($path)
97
    {
98 11
        $normalizedPath = rtrim(
99 11
            str_replace('\\', '/', (string)$path),
100 11
            '/'
101 11
        );
102 11
        $separatorPosition = mb_strrpos($normalizedPath, '/');
103
104 11
        if ($separatorPosition !== false) {
105 9
            return mb_substr($path, 0, $separatorPosition);
106
        }
107
108 2
        return '';
109
    }
110
111
    /**
112
     * Truncates a string to the number of characters specified.
113
     *
114
     * In order to truncate for an exact length, the $suffix char length must be counted towards the $length. For example
115
     * to have a string which is exactly 255 long with $suffix `...` of 3 chars, then `StringHelper::truncate($string, 252, '...')`
116
     * must be used to ensure you have 255 long string afterwards.
117
     *
118
     * @param string $string The string to truncate.
119
     * @param int $length How many characters from original string to include into truncated string.
120
     * @param string $suffix String to append to the end of truncated string.
121
     * @param string|null $encoding The charset to use, defaults to charset currently used by application.
122
     * @param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
123
     * This parameter is available since version 2.0.1.
124
     * @return string the truncated string.
125
     */
126 1
    public static function truncate($string, $length, $suffix = '...', $encoding = null, $asHtml = false)
127
    {
128 1
        $string = (string)$string;
129
130 1
        if ($encoding === null) {
131 1
            $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
132
        }
133 1
        if ($asHtml) {
134 1
            return static::truncateHtml($string, $length, $suffix, $encoding);
135
        }
136
137 1
        if (mb_strlen($string, $encoding) > $length) {
138 1
            return rtrim(mb_substr($string, 0, $length, $encoding)) . $suffix;
139
        }
140
141 1
        return $string;
142
    }
143
144
    /**
145
     * Truncates a string to the number of words specified.
146
     *
147
     * @param string $string The string to truncate.
148
     * @param int $count How many words from original string to include into truncated string.
149
     * @param string $suffix String to append to the end of truncated string.
150
     * @param bool $asHtml Whether to treat the string being truncated as HTML and preserve proper HTML tags.
151
     * This parameter is available since version 2.0.1.
152
     * @return string the truncated string.
153
     */
154 1
    public static function truncateWords($string, $count, $suffix = '...', $asHtml = false)
155
    {
156 1
        if ($asHtml) {
157 1
            return static::truncateHtml($string, $count, $suffix);
158
        }
159
160 1
        $words = preg_split('/(\s+)/u', trim($string), 0, PREG_SPLIT_DELIM_CAPTURE);
161 1
        if (count($words) / 2 > $count) {
162 1
            return implode('', array_slice($words, 0, ($count * 2) - 1)) . $suffix;
163
        }
164
165 1
        return $string;
166
    }
167
168
    /**
169
     * Truncate a string while preserving the HTML.
170
     *
171
     * @param string $string The string to truncate
172
     * @param int $count The counter
173
     * @param string $suffix String to append to the end of the truncated string.
174
     * @param string|bool $encoding Encoding flag or charset.
175
     * @return string
176
     * @since 2.0.1
177
     */
178 2
    protected static function truncateHtml($string, $count, $suffix, $encoding = false)
179
    {
180 2
        $config = \HTMLPurifier_Config::create(null);
181 2
        if (Yii::$app !== null) {
182
            $config->set('Cache.SerializerPath', Yii::$app->getRuntimePath());
183
        }
184 2
        $lexer = \HTMLPurifier_Lexer::create($config);
185 2
        $tokens = $lexer->tokenizeHTML($string, $config, new \HTMLPurifier_Context());
186 2
        $openTokens = [];
187 2
        $totalCount = 0;
188 2
        $depth = 0;
189 2
        $truncated = [];
190 2
        foreach ($tokens as $token) {
191 2
            if ($token instanceof \HTMLPurifier_Token_Start) { //Tag begins
192 2
                $openTokens[$depth] = $token->name;
193 2
                $truncated[] = $token;
194 2
                ++$depth;
195 2
            } elseif ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) { //Text
196 2
                if (false === $encoding) {
197 1
                    preg_match('/^(\s*)/um', $token->data, $prefixSpace) ?: $prefixSpace = ['', ''];
198 1
                    $token->data = $prefixSpace[1] . self::truncateWords(ltrim($token->data), $count - $totalCount, '');
199 1
                    $currentCount = self::countWords($token->data);
200
                } else {
201 1
                    $token->data = self::truncate($token->data, $count - $totalCount, '', $encoding);
0 ignored issues
show
Bug introduced by
It seems like $encoding can also be of type true; however, parameter $encoding of yii\helpers\BaseStringHelper::truncate() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

201
                    $token->data = self::truncate($token->data, $count - $totalCount, '', /** @scrutinizer ignore-type */ $encoding);
Loading history...
202 1
                    $currentCount = mb_strlen($token->data, $encoding);
0 ignored issues
show
Bug introduced by
It seems like $encoding can also be of type true; however, parameter $encoding of mb_strlen() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

202
                    $currentCount = mb_strlen($token->data, /** @scrutinizer ignore-type */ $encoding);
Loading history...
203
                }
204 2
                $totalCount += $currentCount;
205 2
                $truncated[] = $token;
206 2
            } elseif ($token instanceof \HTMLPurifier_Token_End) { //Tag ends
207 2
                if ($token->name === $openTokens[$depth - 1]) {
208 2
                    --$depth;
209 2
                    unset($openTokens[$depth]);
210 2
                    $truncated[] = $token;
211
                }
212 2
            } elseif ($token instanceof \HTMLPurifier_Token_Empty) { //Self contained tags, i.e. <img/> etc.
213 2
                $truncated[] = $token;
214
            }
215 2
            if ($totalCount >= $count) {
216 2
                if (0 < count($openTokens)) {
217 2
                    krsort($openTokens);
218 2
                    foreach ($openTokens as $name) {
219 2
                        $truncated[] = new \HTMLPurifier_Token_End($name);
220
                    }
221
                }
222 2
                break;
223
            }
224
        }
225 2
        $context = new \HTMLPurifier_Context();
226 2
        $generator = new \HTMLPurifier_Generator($config, $context);
227 2
        return $generator->generateFromTokens($truncated) . ($totalCount >= $count ? $suffix : '');
228
    }
229
230
    /**
231
     * Check if given string starts with specified substring. Binary and multibyte safe.
232
     *
233
     * @param string $string Input string
234
     * @param string $with Part to search inside the $string
235
     * @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, `$with` must
236
     * exactly match the starting of the string in order to get a true value.
237
     * @return bool Returns true if first input starts with second input, false otherwise
238
     */
239 20
    public static function startsWith($string, $with, $caseSensitive = true)
240
    {
241 20
        $string = (string)$string;
242 20
        $with = (string)$with;
243
244 20
        if (!$bytes = static::byteLength($with)) {
245 3
            return true;
246
        }
247 17
        if ($caseSensitive) {
248 16
            return strncmp($string, $with, $bytes) === 0;
249
        }
250
251 15
        $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
252 15
        $string = static::byteSubstr($string, 0, $bytes);
253
254 15
        return mb_strtolower($string, $encoding) === mb_strtolower($with, $encoding);
255
    }
256
257
    /**
258
     * Check if given string ends with specified substring. Binary and multibyte safe.
259
     *
260
     * @param string $string Input string to check
261
     * @param string $with Part to search inside of the `$string`.
262
     * @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, `$with` must
263
     * exactly match the ending of the string in order to get a true value.
264
     * @return bool Returns true if first input ends with second input, false otherwise
265
     */
266 30
    public static function endsWith($string, $with, $caseSensitive = true)
267
    {
268 30
        $string = (string)$string;
269 30
        $with = (string)$with;
270
271 30
        if (!$bytes = static::byteLength($with)) {
272 3
            return true;
273
        }
274 27
        if ($caseSensitive) {
275
            // Warning check, see https://php.net/substr-compare#refsect1-function.substr-compare-returnvalues
276 16
            if (static::byteLength($string) < $bytes) {
277 3
                return false;
278
            }
279
280 13
            return substr_compare($string, $with, -$bytes, $bytes) === 0;
281
        }
282
283 25
        $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
284 25
        $string = static::byteSubstr($string, -$bytes);
285
286 25
        return mb_strtolower($string, $encoding) === mb_strtolower($with, $encoding);
287
    }
288
289
    /**
290
     * Explodes string into array, optionally trims values and skips empty ones.
291
     *
292
     * @param string $string String to be exploded.
293
     * @param string $delimiter Delimiter. Default is ','.
294
     * @param mixed $trim Whether to trim each element. Can be:
295
     *   - boolean - to trim normally;
296
     *   - string - custom characters to trim. Will be passed as a second argument to `trim()` function.
297
     *   - callable - will be called for each value instead of trim. Takes the only argument - value.
298
     * @param bool $skipEmpty Whether to skip empty strings between delimiters. Default is false.
299
     * @return array
300
     * @since 2.0.4
301
     */
302 1
    public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false)
303
    {
304 1
        $result = explode($delimiter, $string);
305 1
        if ($trim !== false) {
306 1
            if ($trim === true) {
307 1
                $trim = 'trim';
308 1
            } elseif (!is_callable($trim)) {
309 1
                $trim = function ($v) use ($trim) {
310 1
                    return trim($v, $trim);
311 1
                };
312
            }
313 1
            $result = array_map($trim, $result);
314
        }
315 1
        if ($skipEmpty) {
316
            // Wrapped with array_values to make array keys sequential after empty values removing
317 1
            $result = array_values(array_filter($result, function ($value) {
318 1
                return $value !== '';
319 1
            }));
320
        }
321
322 1
        return $result;
323
    }
324
325
    /**
326
     * Counts words in a string.
327
     *
328
     * @param string $string the text to calculate
329
     * @return int
330
     * @since 2.0.8
331
     */
332 2
    public static function countWords($string)
333
    {
334 2
        return count(preg_split('/\s+/u', $string, 0, PREG_SPLIT_NO_EMPTY));
335
    }
336
337
    /**
338
     * Returns string representation of number value with replaced commas to dots, if decimal point
339
     * of current locale is comma.
340
     *
341
     * @param int|float|string $value the value to normalize.
342
     * @return string
343
     * @since 2.0.11
344
     */
345 34
    public static function normalizeNumber($value)
346
    {
347 34
        $value = (string) $value;
348
349 34
        $localeInfo = localeconv();
350 34
        $decimalSeparator = isset($localeInfo['decimal_point']) ? $localeInfo['decimal_point'] : null;
351
352 34
        if ($decimalSeparator !== null && $decimalSeparator !== '.') {
353 4
            $value = str_replace($decimalSeparator, '.', $value);
354
        }
355
356 34
        return $value;
357
    }
358
359
    /**
360
     * Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
361
     *
362
     * > Note: Base 64 padding `=` may be at the end of the returned string.
363
     * > `=` is not transparent to URL encoding.
364
     *
365
     * @param string $input the string to encode.
366
     * @return string encoded string.
367
     * @see https://tools.ietf.org/html/rfc4648#page-7
368
     * @since 2.0.12
369
     */
370 112
    public static function base64UrlEncode($input)
371
    {
372 112
        return strtr(base64_encode($input), '+/', '-_');
373
    }
374
375
    /**
376
     * Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
377
     *
378
     * @param string $input encoded string.
379
     * @return string decoded string.
380
     * @see https://tools.ietf.org/html/rfc4648#page-7
381
     * @since 2.0.12
382
     */
383 13
    public static function base64UrlDecode($input)
384
    {
385 13
        return base64_decode(strtr($input, '-_', '+/'));
386
    }
387
388
    /**
389
     * Safely casts a float to string independent of the current locale.
390
     * The decimal separator will always be `.`.
391
     *
392
     * @param float|int $number a floating point number or integer.
393
     * @return string the string representation of the number.
394
     * @since 2.0.13
395
     */
396 10
    public static function floatToString($number)
397
    {
398
        // . and , are the only decimal separators known in ICU data,
399
        // so its safe to call str_replace here
400 10
        return str_replace(',', '.', (string) $number);
401
    }
402
403
    /**
404
     * Checks if the passed string would match the given shell wildcard pattern.
405
     * This function emulates [[fnmatch()]], which may be unavailable at certain environment, using PCRE.
406
     *
407
     * @param string $pattern the shell wildcard pattern.
408
     * @param string $string the tested string.
409
     * @param array $options options for matching. Valid options are:
410
     *
411
     * - caseSensitive: bool, whether pattern should be case sensitive. Defaults to `true`.
412
     * - escape: bool, whether backslash escaping is enabled. Defaults to `true`.
413
     * - filePath: bool, whether slashes in string only matches slashes in the given pattern. Defaults to `false`.
414
     *
415
     * @return bool whether the string matches pattern or not.
416
     * @since 2.0.14
417
     */
418 244
    public static function matchWildcard($pattern, $string, $options = [])
419
    {
420 244
        if ($pattern === '*' && empty($options['filePath'])) {
421 5
            return true;
422
        }
423
424 240
        $replacements = [
425 240
            '\\\\\\\\' => '\\\\',
426 240
            '\\\\\\*' => '[*]',
427 240
            '\\\\\\?' => '[?]',
428 240
            '\*' => '.*',
429 240
            '\?' => '.',
430 240
            '\[\!' => '[^',
431 240
            '\[' => '[',
432 240
            '\]' => ']',
433 240
            '\-' => '-',
434 240
        ];
435
436 240
        if (isset($options['escape']) && !$options['escape']) {
437 9
            unset($replacements['\\\\\\\\']);
438 9
            unset($replacements['\\\\\\*']);
439 9
            unset($replacements['\\\\\\?']);
440
        }
441
442 240
        if (!empty($options['filePath'])) {
443 12
            $replacements['\*'] = '[^/\\\\]*';
444 12
            $replacements['\?'] = '[^/\\\\]';
445
        }
446
447 240
        $pattern = strtr(preg_quote($pattern, '#'), $replacements);
448 240
        $pattern = '#^' . $pattern . '$#us';
449
450 240
        if (isset($options['caseSensitive']) && !$options['caseSensitive']) {
451 2
            $pattern .= 'i';
452
        }
453
454 240
        return preg_match($pattern, (string)$string) === 1;
455
    }
456
457
    /**
458
     * This method provides a unicode-safe implementation of built-in PHP function `ucfirst()`.
459
     *
460
     * @param string $string the string to be proceeded
461
     * @param string $encoding Optional, defaults to "UTF-8"
462
     * @return string
463
     * @see https://www.php.net/manual/en/function.ucfirst.php
464
     * @since 2.0.16
465
     * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
466
     */
467 227
    public static function mb_ucfirst($string, $encoding = 'UTF-8')
468
    {
469 227
        $firstChar = mb_substr((string)$string, 0, 1, $encoding);
470 227
        $rest = mb_substr((string)$string, 1, null, $encoding);
471
472 227
        return mb_strtoupper($firstChar, $encoding) . $rest;
473
    }
474
475
    /**
476
     * This method provides a unicode-safe implementation of built-in PHP function `ucwords()`.
477
     *
478
     * @param string $string the string to be proceeded
479
     * @param string $encoding Optional, defaults to "UTF-8"
480
     * @return string
481
     * @see https://www.php.net/manual/en/function.ucwords
482
     * @since 2.0.16
483
     * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
484
     */
485 224
    public static function mb_ucwords($string, $encoding = 'UTF-8')
486
    {
487 224
        $string = (string) $string;
488 224
        if (empty($string)) {
489 3
            return $string;
490
        }
491
492 221
        $parts = preg_split('/(\s+\W+\s+|^\W+\s+|\s+)/u', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
493 221
        $ucfirstEven = trim(mb_substr($parts[0], -1, 1, $encoding)) === '';
494 221
        foreach ($parts as $key => $value) {
495 221
            $isEven = (bool)($key % 2);
496 221
            if ($ucfirstEven === $isEven) {
497 221
                $parts[$key] = static::mb_ucfirst($value, $encoding);
498
            }
499
        }
500
501 221
        return implode('', $parts);
502
    }
503
504
    /**
505
     * Masks a portion of a string with a repeated character.
506
     * This method is multibyte-safe.
507
     *
508
     * @param string $string The input string.
509
     * @param int $start The starting position from where to begin masking.
510
     *                   This can be a positive or negative integer.
511
     *                   Positive values count from the beginning,
512
     *                   negative values count from the end of the string.
513
     * @param int $length The length of the section to be masked.
514
     *                    The masking will start from the $start position
515
     *                    and continue for $length characters.
516
     * @param string $mask The character to use for masking. The default is '*'.
517
     * @return string The masked string.
518
     */
519 1
    public static function mask($string, $start, $length, $mask = '*')
520
    {
521 1
        $strLength = mb_strlen($string, 'UTF-8');
522
523
        // Return original string if start position is out of bounds
524 1
        if ($start >= $strLength || $start < -$strLength) {
525 1
            return $string;
526
        }
527
528 1
        $masked = mb_substr($string, 0, $start, 'UTF-8');
529 1
        $masked .= str_repeat($mask, abs($length));
0 ignored issues
show
Bug introduced by
It seems like abs($length) can also be of type double; however, parameter $times of str_repeat() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

529
        $masked .= str_repeat($mask, /** @scrutinizer ignore-type */ abs($length));
Loading history...
530 1
        $masked .= mb_substr($string, $start + abs($length), null, 'UTF-8');
0 ignored issues
show
Bug introduced by
$start + abs($length) of type double is incompatible with the type integer expected by parameter $start of mb_substr(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

530
        $masked .= mb_substr($string, /** @scrutinizer ignore-type */ $start + abs($length), null, 'UTF-8');
Loading history...
531
532 1
        return $masked;
533
    }
534
535
    /**
536
     * Returns the portion of the string that lies between the first occurrence of the start string
537
     * and the last occurrence of the end string after that.
538
     *
539
     * @param string $string The input string.
540
     * @param string $start The string marking the start of the portion to extract.
541
     * @param string $end The string marking the end of the portion to extract.
542
     * @return string|null The portion of the string between the first occurrence of
543
     * start and the last occurrence of end, or null if either start or end cannot be found.
544
     */
545 12
    public static function findBetween($string, $start, $end)
546
    {
547 12
        $startPos = mb_strpos($string, $start);
548
549 12
        if ($startPos === false) {
550 3
            return null;
551
        }
552
553 9
        $startPos += mb_strlen($start);
554 9
        $endPos = mb_strrpos($string, $end, $startPos);
555
556 9
        if ($endPos === false) {
557 2
            return null;
558
        }
559
560 7
        return mb_substr($string, $startPos, $endPos - $startPos);
561
    }
562
}
563