Add mb_ucwords

master
Julien Rosset 1 year ago
parent f60731b842
commit 2f53e4876a

@ -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}

@ -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}
*

Loading…
Cancel
Save