Skip to content

Commit b32193b

Browse files
[Fix] Str::Mask() for consecutively repeating chars (#42295) (#42956)
- Add some additional test cases to verify behaviour for more than 2 repeating characters. - Add some cases for testing the masking from the start of the string, before the start of the string and end of string. (cherry picked from commit a917528) Co-authored-by: Remy Bos <[email protected]>
1 parent 0131fd5 commit b32193b

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

src/Illuminate/Support/Str.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -437,10 +437,18 @@ public static function mask($string, $character, $index, $length = null, $encodi
437437
return $string;
438438
}
439439

440-
$start = mb_substr($string, 0, mb_strpos($string, $segment, 0, $encoding), $encoding);
441-
$end = mb_substr($string, mb_strpos($string, $segment, 0, $encoding) + mb_strlen($segment, $encoding));
440+
$strlen = mb_strlen($string, $encoding);
441+
$startIndex = $index;
442442

443-
return $start.str_repeat(mb_substr($character, 0, 1, $encoding), mb_strlen($segment, $encoding)).$end;
443+
if ($index < 0) {
444+
$startIndex = $index < -$strlen ? 0 : $strlen + $index;
445+
}
446+
447+
$start = mb_substr($string, 0, $startIndex, $encoding);
448+
$segmentLen = mb_strlen($segment, $encoding);
449+
$end = mb_substr($string, $startIndex + $segmentLen);
450+
451+
return $start.str_repeat(mb_substr($character, 0, 1, $encoding), $segmentLen).$end;
444452
}
445453

446454
/**

tests/Support/SupportStrTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,19 @@ public function testMask()
508508

509509
$this->assertSame('这是一***', Str::mask('这是一段中文', '*', 3));
510510
$this->assertSame('**一段中文', Str::mask('这是一段中文', '*', 0, 2));
511+
512+
$this->assertSame('ma*[email protected]', Str::mask('[email protected]', '*', 2, 1));
513+
$this->assertSame('ma***email.com', Str::mask('[email protected]', '*', 2, 3));
514+
$this->assertSame('ma************', Str::mask('[email protected]', '*', 2));
515+
516+
$this->assertSame('mari*@email.com', Str::mask('[email protected]', '*', 4, 1));
517+
$this->assertSame('tamar*@email.com', Str::mask('[email protected]', '*', 5, 1));
518+
519+
$this->assertSame('*[email protected]', Str::mask('[email protected]', '*', 0, 1));
520+
$this->assertSame('[email protected]*', Str::mask('[email protected]', '*', -1, 1));
521+
$this->assertSame('[email protected]*', Str::mask('[email protected]', '*', -1));
522+
$this->assertSame('***************', Str::mask('[email protected]', '*', -15));
523+
$this->assertSame('***************', Str::mask('[email protected]', '*', 0));
511524
}
512525

513526
public function testMatch()

0 commit comments

Comments
 (0)