Skip to content

Commit

Permalink
Add function addCharAtInterval() to Str class
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashraam committed Aug 27, 2024
1 parent 5263f9d commit aec63f9
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Illuminate/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,19 @@ public static function afterLast($subject, $search)
return substr($subject, $position + strlen($search));
}

/**
* Return the given string with a custom character every X character.
*
* @param string $subject
* @param string $char
* @param int $length
* @return string
*/
public static function addCharAtInterval($subject, $char, $length = 1)
{
return implode($char, str_split($subject, $length));
}

/**
* Transliterate a UTF-8 value to ASCII.
*
Expand Down
12 changes: 12 additions & 0 deletions src/Illuminate/Support/Stringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,18 @@ public function after($search)
return new static(Str::after($this->value, $search));
}

/**
* Return the given string with a custom character every X character.
*
* @param $char
* @param $length
* @return static
*/
public function addCharAtInterval($char, $length = 1)
{
return new static(Str::addCharAtInterval($this->value, $char, $length));
}

/**
* Return the remainder of a string after the last occurrence of a given value.
*
Expand Down
6 changes: 6 additions & 0 deletions tests/Support/SupportStrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@

class SupportStrTest extends TestCase
{
public function testItAddsACustomCharacterEveryXTimes(): void
{
$this->assertSame('12 34 56 78 90', Str::addCharAtInterval('1234567890', ' ', 2));
$this->assertSame('123-456-789', Str::addCharAtInterval('123456789', '-', 3));
}

public function testStringCanBeLimitedByWords(): void
{
$this->assertSame('Taylor...', Str::words('Taylor Otwell', 1));
Expand Down
6 changes: 6 additions & 0 deletions tests/Support/SupportStringableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ class_basename(static::class),
);
}

public function testItAddsACustomCharacterEveryXTimes()
{
$this->assertSame('12 34 56 78 90', (string) $this->stringable('1234567890')->addCharAtInterval(' ', 2));
$this->assertSame('123-456-789', (string) $this->stringable('123456789')->addCharAtInterval('-', 3));
}

public function testIsAscii()
{
$this->assertTrue($this->stringable('A')->isAscii());
Expand Down

0 comments on commit aec63f9

Please sign in to comment.