From 591bb23a3c5fed0d89a5638a54c3d99df0554650 Mon Sep 17 00:00:00 2001 From: Jeroen van Rensen <46967616+jeroenvanrensen@users.noreply.github.com> Date: Wed, 14 Apr 2021 21:33:59 +0200 Subject: [PATCH] [8.x] Add a wordCount() string helper (#36990) * Add a wordCount() string helper * Update Str.php * Update Stringable.php Co-authored-by: Taylor Otwell --- src/Illuminate/Support/Str.php | 11 +++++++++++ src/Illuminate/Support/Stringable.php | 10 ++++++++++ tests/Support/SupportStrTest.php | 6 ++++++ tests/Support/SupportStringableTest.php | 6 ++++++ 4 files changed, 33 insertions(+) diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index 1e6b849cc8a9..37e3fd082956 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -766,6 +766,17 @@ public static function ucfirst($string) return static::upper(static::substr($string, 0, 1)).static::substr($string, 1); } + /** + * Get the number of words a string contains. + * + * @param string $string + * @return int + */ + public static function wordCount($string) + { + return str_word_count($string); + } + /** * Generate a UUID (version 4). * diff --git a/src/Illuminate/Support/Stringable.php b/src/Illuminate/Support/Stringable.php index 79d5a9160215..290914bc32a1 100644 --- a/src/Illuminate/Support/Stringable.php +++ b/src/Illuminate/Support/Stringable.php @@ -756,6 +756,16 @@ public function words($words = 100, $end = '...') return new static(Str::words($this->value, $words, $end)); } + /** + * Get the number of words a string contains. + * + * @return int + */ + public function wordCount() + { + return str_word_count($this->value); + } + /** * Dump the string. * diff --git a/tests/Support/SupportStrTest.php b/tests/Support/SupportStrTest.php index f120708968dc..d8c744b37c70 100755 --- a/tests/Support/SupportStrTest.php +++ b/tests/Support/SupportStrTest.php @@ -494,6 +494,12 @@ public function testPadRight() $this->assertSame('Alien ', Str::padRight('Alien', 10)); } + public function testWordCount() + { + $this->assertEquals(2, Str::wordCount('Hello, world!')); + $this->assertEquals(10, Str::wordCount('Hi, this is my first contribution to the Laravel framework.')); + } + public function validUuidList() { return [ diff --git a/tests/Support/SupportStringableTest.php b/tests/Support/SupportStringableTest.php index be88413d750a..70916a0458b9 100644 --- a/tests/Support/SupportStringableTest.php +++ b/tests/Support/SupportStringableTest.php @@ -608,4 +608,10 @@ public function testRepeat() $this->assertSame('aaaaa', (string) $this->stringable('a')->repeat(5)); $this->assertSame('', (string) $this->stringable('')->repeat(5)); } + + public function testWordCount() + { + $this->assertEquals(2, $this->stringable('Hello, world!')->wordCount()); + $this->assertEquals(10, $this->stringable('Hi, this is my first contribution to the Laravel framework.')->wordCount()); + } }