Skip to content

Commit 9fe1f12

Browse files
authored
[12.x] Add ucwords to Str and Stringable (laravel#57581)
* feat: add ucwords to Str and Stringable * refactor: match native ucwords definition * test: Str::ucwords() * test: acronym preservation and custom separator for Str::ucwords()
1 parent 599f674 commit 9fe1f12

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

src/Illuminate/Support/Str.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1827,6 +1827,22 @@ public static function ucfirst($string)
18271827
return static::upper(static::substr($string, 0, 1)).static::substr($string, 1);
18281828
}
18291829

1830+
/**
1831+
* Capitalize the first character of each word in a string.
1832+
*
1833+
* @param string $string
1834+
* @param string $separators
1835+
* @return string
1836+
*/
1837+
public static function ucwords($string, $separators = " \t\r\n\f\v")
1838+
{
1839+
$pattern = '/(^|['.preg_quote($separators, '/').'])(\p{Ll})/u';
1840+
1841+
return preg_replace_callback($pattern, function ($matches) {
1842+
return $matches[1].mb_strtoupper($matches[2]);
1843+
}, $string);
1844+
}
1845+
18301846
/**
18311847
* Split a string into pieces by uppercase characters.
18321848
*

src/Illuminate/Support/Stringable.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1107,6 +1107,16 @@ public function ucfirst()
11071107
return new static(Str::ucfirst($this->value));
11081108
}
11091109

1110+
/**
1111+
* Capitalize the first character of each word in a string.
1112+
*
1113+
* @return static
1114+
*/
1115+
public function ucwords()
1116+
{
1117+
return new static(Str::ucwords($this->value));
1118+
}
1119+
11101120
/**
11111121
* Split a string by uppercase characters.
11121122
*

tests/Support/SupportStrTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1291,6 +1291,16 @@ public function testUcfirst()
12911291
$this->assertSame('Мама мыла раму', Str::ucfirst('мама мыла раму'));
12921292
}
12931293

1294+
public function testUcwords()
1295+
{
1296+
$this->assertSame('Laravel', Str::ucwords('laravel'));
1297+
$this->assertSame('Laravel Framework', Str::ucwords('laravel framework'));
1298+
$this->assertSame('Laravel-Framework', Str::ucwords('laravel-framework', '-'));
1299+
$this->assertSame('Мама', Str::ucwords('мама'));
1300+
$this->assertSame('Мама Мыла Раму', Str::ucwords('мама мыла раму'));
1301+
$this->assertSame('JJ Watt', Str::ucwords('JJ watt'));
1302+
}
1303+
12941304
public function testUcsplit()
12951305
{
12961306
$this->assertSame(['Laravel_p_h_p_framework'], Str::ucsplit('Laravel_p_h_p_framework'));

0 commit comments

Comments
 (0)