Added StringHelper::countWords() that given a string returns number of words in it

This commit is contained in:
Alexander Makarov
2016-03-16 01:41:57 +03:00
parent b6d26a12e9
commit c17f887583
3 changed files with 22 additions and 0 deletions

View File

@ -27,6 +27,7 @@ Yii Framework 2 Change Log
- Enh #10764: `yii\helpers\Html::tag()` and `::beginTag()` return content without any HTML when the `$tag` attribute is `false` or `null` (pana1990)
- Enh #10941: Added `yii\helpers\ArrayHelper::isTraversable`, added support for traversable selections for dropdownList, radioList and checkboxList in `yii\helpers\Html` (sammousa)
- Eng #10976: `Inflector::transliterate()` now uses `strtr` instead of `str_replace` (DrDeath72)
- Enh: Added `StringHelper::countWords()` that given a string returns number of words in it (samdark)
- Bug #11040: Check parameter 'recursive' and disable recursive copying with option 'recursive' => false in method BaseFileHelper::copyDirectory (Ni-san)
- Chg: HTMLPurifier dependency updated to `~4.6` (samdark)
- Chg #10726: Added `yii\rbac\ManagerInterface::canAddChild()` (dkhlystov, samdark)

View File

@ -270,4 +270,16 @@ class BaseStringHelper
}
return $result;
}
/**
* Counts words in a string
* @since 2.0.8
*
* @param string $string
* @return integer
*/
public static function countWords($string)
{
return count(preg_split('/\s+/u', $string, null, PREG_SPLIT_NO_EMPTY));
}
}

View File

@ -240,4 +240,13 @@ class StringHelperTest extends TestCase
$this->assertEquals(['It/', ' is?', ' a', ' test with rtrim'], StringHelper::explode("It/, is?, a , test with rtrim", ',', 'rtrim'));
$this->assertEquals(['It', ' is', ' a ', ' test with closure'], StringHelper::explode("It/, is?, a , test with closure", ',', function ($value) { return trim($value, '/?'); }));
}
public function testWordCount()
{
$this->assertEquals(3, StringHelper::countWords('china 中国 ㄍㄐㄋㄎㄌ'));
$this->assertEquals(4, StringHelper::countWords('и много тут слов?'));
$this->assertEquals(4, StringHelper::countWords("и\rмного\r\nтут\nслов?"));
$this->assertEquals(1, StringHelper::countWords('крем-брюле'));
$this->assertEquals(1, StringHelper::countWords(' слово '));
}
}