Skip to content

Commit 5606b05

Browse files
committed
Fix the sub method for new lines and consecutive spaces
1 parent dcc7389 commit 5606b05

1 file changed

Lines changed: 9 additions & 13 deletions

File tree

src/Str.php

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1456,31 +1456,27 @@ public static function start($value, $prefix)
14561456
*/
14571457
public static function sub($string, $start, $length = null, $encoding = 'UTF-8')
14581458
{
1459-
preg_match_all('/./u', $string, $matches);
1459+
preg_match_all('/./us', $string, $matches);
14601460
$chars = $matches[0];
14611461
$filteredChars = [];
1462+
14621463
foreach ($chars as $char) {
14631464
if (preg_match('/\p{M}/u', $char) && !empty($filteredChars)) {
1465+
// Add diacritic combinations to the previous character.
14641466
$filteredChars[count($filteredChars) - 1] .= $char;
14651467
} else {
1466-
$filteredChars[] = $char;
1468+
// Ensuring that spaces and new lines are not removed.
1469+
if (!preg_match('/\s/u', $char) || $char === " " || $char === "\n" || $char === "\r" || $char === "\t") {
1470+
$filteredChars[] = $char;
1471+
}
14671472
}
14681473
}
1474+
14691475
if (is_null($length)) {
14701476
$length = count($filteredChars) - $start;
14711477
}
1472-
return implode('', array_slice($filteredChars, $start, $length));
14731478

1474-
//return mb_substr($string, $start, $length, $encoding);
1475-
//return mb_convert_encoding(
1476-
// substr(
1477-
// mb_convert_encoding($string, 'UTF-16'),
1478-
// $start << 1,
1479-
// $length === null ? null : ($length << 1),
1480-
// ),
1481-
// 'UTF-8',
1482-
// 'UTF-16',
1483-
//);
1479+
return implode('', array_slice($filteredChars, $start, $length));
14841480
}
14851481

14861482
/**

0 commit comments

Comments
 (0)