Skip to content

Commit

Permalink
[8.x] Add a wordCount() string helper (#36990)
Browse files Browse the repository at this point in the history
* Add a wordCount() string helper

* Update Str.php

* Update Stringable.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
jeroenvanrensen and taylorotwell committed Apr 14, 2021
1 parent a106b93 commit 591bb23
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Illuminate/Support/Str.php
Expand Up @@ -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).
*
Expand Down
10 changes: 10 additions & 0 deletions src/Illuminate/Support/Stringable.php
Expand Up @@ -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.
*
Expand Down
6 changes: 6 additions & 0 deletions tests/Support/SupportStrTest.php
Expand Up @@ -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 [
Expand Down
6 changes: 6 additions & 0 deletions tests/Support/SupportStringableTest.php
Expand Up @@ -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());
}
}

0 comments on commit 591bb23

Please sign in to comment.