diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index 164018788683..235dbc0cc520 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -1747,11 +1747,19 @@ public static function substrCount($haystack, $needle, $offset = 0, $length = nu */ public static function substrReplace($string, $replace, $offset = 0, $length = null) { - if ($length === null) { - $length = strlen($string); + $encoding = 'UTF-8'; + $strlen = mb_strlen($string, $encoding); + + if ($offset < 0) { + $offset = $offset < -$strlen ? 0 : $strlen + $offset; } - return substr_replace($string, $replace, $offset, $length); + $length = is_null($length) ? $strlen - $offset : max($length, 0); + + $start = mb_substr($string, 0, $offset, $encoding); + $end = mb_substr($string, $offset + $length, $strlen - ($offset + $length), $encoding); + + return $start.$replace.$end; } /** diff --git a/tests/Support/SupportStrTest.php b/tests/Support/SupportStrTest.php index 425966353d29..6a646c70c475 100755 --- a/tests/Support/SupportStrTest.php +++ b/tests/Support/SupportStrTest.php @@ -1262,6 +1262,8 @@ public function testSubstrReplace() $this->assertSame('12:00', Str::substrReplace('1200', ':', 2, 0)); $this->assertSame('The Laravel Framework', Str::substrReplace('The Framework', 'Laravel ', 4, 0)); $this->assertSame('Laravel – The PHP Framework for Web Artisans', Str::substrReplace('Laravel Framework', '– The PHP Framework for Web Artisans', 8)); + $this->assertSame('Laravel – PHP 框架的网络专家', Str::substrReplace('Laravel 的网络专家', '– PHP 框架', 8, 0)); + $this->assertSame('Laravel – PHP Фреймворк для веб-мастеров', Str::substrReplace('Laravel для веб-мастеров', ' – PHP Фреймворк', 7, 0)); } public function testTake()