Skip to content

Commit 4b1344d

Browse files
Fix substrReplace to be multibyte safe (#57936)
* Fix substrReplace to be multibyte safe * Apply code style fixes * formatting --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent aa758b0 commit 4b1344d

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/Illuminate/Support/Str.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1748,10 +1748,12 @@ public static function substrCount($haystack, $needle, $offset = 0, $length = nu
17481748
public static function substrReplace($string, $replace, $offset = 0, $length = null)
17491749
{
17501750
if ($length === null) {
1751-
$length = strlen($string);
1751+
$length = static::length($string);
17521752
}
17531753

1754-
return substr_replace($string, $replace, $offset, $length);
1754+
return mb_substr($string, 0, $offset)
1755+
.$replace
1756+
.mb_substr($string, $offset + $length);
17551757
}
17561758

17571759
/**

tests/Support/SupportStrTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1275,6 +1275,12 @@ public function testSubstrReplace()
12751275
$this->assertSame('Laravel – The PHP Framework for Web Artisans', Str::substrReplace('Laravel Framework', '– The PHP Framework for Web Artisans', 8));
12761276
}
12771277

1278+
public function testSubstrReplaceWithMultibyte()
1279+
{
1280+
$this->assertSame('kengä', Str::substrReplace('kenkä', 'ng', -3, 2));
1281+
$this->assertSame('kenga', Str::substrReplace('kenka', 'ng', -3, 2));
1282+
}
1283+
12781284
public function testTake()
12791285
{
12801286
$this->assertSame('ab', Str::take('abcdef', 2));

0 commit comments

Comments
 (0)