Skip to content

Commit bb068a7

Browse files
committed
feature: support multibyte strings in substrReplace
refs: #57838
1 parent d645617 commit bb068a7

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

src/Illuminate/Support/Str.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1747,11 +1747,19 @@ public static function substrCount($haystack, $needle, $offset = 0, $length = nu
17471747
*/
17481748
public static function substrReplace($string, $replace, $offset = 0, $length = null)
17491749
{
1750-
if ($length === null) {
1751-
$length = mb_strlen($string);
1750+
$encoding = 'UTF-8';
1751+
$strlen = mb_strlen($string, $encoding);
1752+
1753+
if ($offset < 0) {
1754+
$offset = $offset < -$strlen ? 0 : $strlen + $offset;
17521755
}
17531756

1754-
return substr_replace($string, $replace, $offset, $length);
1757+
$length = is_null($length) ? $strlen - $offset : max($length, 0);
1758+
1759+
$start = mb_substr($string, 0, $offset, $encoding);
1760+
$end = mb_substr($string, $offset + $length, $strlen - ($offset + $length), $encoding);
1761+
1762+
return $start . $replace . $end;
17551763
}
17561764

17571765
/**

tests/Support/SupportStrTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1262,6 +1262,8 @@ public function testSubstrReplace()
12621262
$this->assertSame('12:00', Str::substrReplace('1200', ':', 2, 0));
12631263
$this->assertSame('The Laravel Framework', Str::substrReplace('The Framework', 'Laravel ', 4, 0));
12641264
$this->assertSame('Laravel – The PHP Framework for Web Artisans', Str::substrReplace('Laravel Framework', '– The PHP Framework for Web Artisans', 8));
1265+
$this->assertSame('Laravel – PHP 框架的网络专家', Str::substrReplace('Laravel 的网络专家', '– PHP 框架', 8, 0));
1266+
$this->assertSame('Laravel – PHP Фреймворк для веб-мастеров', Str::substrReplace('Laravel для веб-мастеров', ' – PHP Фреймворк', 7, 0));
12651267
}
12661268

12671269
public function testTake()

0 commit comments

Comments
 (0)