From 2f53e4876a3a0b817f231890a4ffb60c6dee2ff3 Mon Sep 17 00:00:00 2001 From: Julien Rosset Date: Thu, 31 Jul 2025 11:33:44 +0200 Subject: [PATCH] Add mb_ucwords --- boostrap.php | 12 ++++++++++++ src/MbstringExtended.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/boostrap.php b/boostrap.php index c43e212..98dd47f 100644 --- a/boostrap.php +++ b/boostrap.php @@ -27,6 +27,18 @@ if (!function_exists('mb_ucfirst')) { return MbstringExtended::ucfirst($string); } } +if (!function_exists('mb_ucwords')) { + /** + * Multi-bytes implementation for {@see https://www.php.net/manual/function.ucwords.php ucwords} + * + * @param string $string The input string + * + * @return string The resulting string + */ + function mb_ucwords (string $string): string { + return MbstringExtended::ucwords($string); + } +} if (!function_exists('mb_str_pad')) { /** * Multi-bytes implementation for {@see https://www.php.net/manual/function.str-pad.php str_pad} diff --git a/src/MbstringExtended.php b/src/MbstringExtended.php index c85f6eb..6155e1d 100644 --- a/src/MbstringExtended.php +++ b/src/MbstringExtended.php @@ -28,6 +28,35 @@ final class MbstringExtended { public static function ucfirst (string $string): string { return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1)); } + /** + * Multi-bytes implementation for {@see https://www.php.net/manual/function.ucwords.php ucwords} + * + * @param string $texte The input string + * + * @return string The resulting string + */ + public static function ucwords (string $texte): string { + // mb_convert_case with MB_CASE_TITLE doesn't do the work because force lowercase on others characters: "forgottenPassword" become "Forgottenpassword" + // This version fix the problem: https://stackoverflow.com/a/3337526 + $textChars = preg_split("//u", $texte, -1, PREG_SPLIT_NO_EMPTY); + $result = ""; + $mode = false; + foreach ($textChars as $char) { + $res = preg_match('/\\p{Mn}|\\p{Me}|\\p{Cf}|\\p{Lm}|\\p{Sk}|\\p{Lu}|\\p{Ll}|\\p{Lt}|\\p{Cs}/u', $char) === 1; + if ($mode) { + if (!$res) { + $mode = false; + } + } + elseif ($res) { + $mode = true; + $char = mb_convert_case($char, MB_CASE_TITLE); + } + $result .= $char; + } + + return $result; + } /** * Multi-bytes implementation for {@see https://www.php.net/manual/function.str-pad.php str_pad} *