From c17f887583fae751ea080c55265146e2a1178b70 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 16 Mar 2016 01:41:57 +0300 Subject: [PATCH] Added `StringHelper::countWords()` that given a string returns number of words in it --- framework/CHANGELOG.md | 1 + framework/helpers/BaseStringHelper.php | 12 ++++++++++++ tests/framework/helpers/StringHelperTest.php | 9 +++++++++ 3 files changed, 22 insertions(+) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 37ed2c8245..813c76e9df 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -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) diff --git a/framework/helpers/BaseStringHelper.php b/framework/helpers/BaseStringHelper.php index 6ee5299505..2a0a722c44 100644 --- a/framework/helpers/BaseStringHelper.php +++ b/framework/helpers/BaseStringHelper.php @@ -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)); + } } diff --git a/tests/framework/helpers/StringHelperTest.php b/tests/framework/helpers/StringHelperTest.php index c6fbd9e61d..3f35b53c47 100644 --- a/tests/framework/helpers/StringHelperTest.php +++ b/tests/framework/helpers/StringHelperTest.php @@ -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(' слово ')); + } }