From 24b5f7f12aa03fc252e73e069ab67214e5238e79 Mon Sep 17 00:00:00 2001 From: Dominique Fournier Date: Wed, 14 Jun 2017 11:25:59 +0000 Subject: [PATCH] convert: ucwords in UTF-8 with delimiter git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@3769 bf3deb0d-5f1a-0410-827f-c0cc1f45334c --- Tests/convertTest.php | 36 ++++++++++++++++++++++++++++++++++++ convert.php | 23 ++++++++++++++++++++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/Tests/convertTest.php b/Tests/convertTest.php index 0c1e82a..f9dbd82 100644 --- a/Tests/convertTest.php +++ b/Tests/convertTest.php @@ -22,4 +22,40 @@ class test_convert extends PHPUnit_Framework_TestCase $res = \convert::convertDate ("2017-13-33", "Y-m-d", "d/m/Y", false); $this->assertSame ($res, "2017-13-33"); } + + public function test_ucwords_1 () + { + $res = \convert::ucwords (" test yuyu "); + $this->assertSame ($res, " Test Yuyu "); + } + + public function test_ucwords_2 () + { + $res = \convert::ucwords (""); + $this->assertSame ($res, ""); + } + + public function test_ucwords_3 () + { + $res = \convert::ucwords ("test"); + $this->assertSame ($res, "Test"); + } + + public function test_ucwords_4 () + { + $res = \convert::ucwords ("TEST"); + $this->assertSame ($res, "Test"); + } + + public function test_ucwords_5 () + { + $res = \convert::ucwords ("édouard étienne"); + $this->assertSame ($res, "Édouard Étienne"); + } + + public function test_ucwords_6 () + { + $res = \convert::ucwords ("édou-ard d'étienne", " -'"); + $this->assertSame ($res, "Édou-Ard D'Étienne"); + } } diff --git a/convert.php b/convert.php index e685681..aa14da9 100644 --- a/convert.php +++ b/convert.php @@ -48,7 +48,7 @@ class convert } /** Convert the first char to capital and the rest of the sentence in - * lowercase (like ucfirst, but UTF8 compliant + * lowercase (like ucfirst, but UTF8 compliant) * @param string $str The string to convert */ public static function ucfirst ($str) @@ -56,4 +56,25 @@ class convert $a = mb_strtoupper (mb_substr ($str, 0, 1, 'UTF-8'), 'UTF-8'); return $a . mb_substr ($str, 1, null, 'UTF-8'); } + + /** Convert the first char of each word of a sentence to capital. The word + * delimiter can be provided. + * The sentence is in UTF-8. + * The sentence is converted to lowercase before doing the action (in + * contrary of the original PHP function) + * @param string $str The string to convert + * @param string $delimiters The delimiters (by default " \t\r\n\f\v") + * @return string + */ + public static function ucwords ($str, $delimiters = " \t\r\n\f\v") + { + $str = mb_strtolower ($str, "utf-8"); + $res = ""; + foreach (preg_split ("#([".preg_quote ($delimiters)."]+)#", $str, -1, + PREG_SPLIT_DELIM_CAPTURE) as $tok) + { + $res .= \convert::ucfirst ($tok); + } + return $res; + } }