Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add a wordCount() string helper #36990

Merged
merged 3 commits into from Apr 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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());
}
}