Sunday, 15 September 2013

How to convert the first letter (with a diacritic) of the first word of a sentence in PHP?

How to convert the first letter (with a diacritic) of the first word of a
sentence in PHP?

I need to convert to lowercase some strings/sentences, like this:
"șef de cabinet", then to convert to uppercase the first letter of
the first word (with a diacritic) of these strings. I found a function,
but it converts the first letter of every word from the string. How to
adapt it to my needs?
This is the code:
function sentence_case( $s ) {
$s = mb_convert_case( $s, MB_CASE_LOWER, 'UTF-8' );
$arr = preg_split("//u", $s, -1, PREG_SPLIT_NO_EMPTY);
$result = "";
$mode = false;
foreach ($arr as $char) {
$res = preg_match(
'/\\p{Mn}|\\p{Me}|\\p{Cf}|\\p{Lm}|\\p{Sk}|\\p{Lu}|\\p{Ll}|'.
'\\p{Lt}|\\p{Sk}|\\p{Cs}/u', $char) == 1;
if ($mode) {
if (!$res)
$mode = false;
}
elseif ($res) {
$mode = true;
$char = mb_convert_case($char, MB_CASE_TITLE, "UTF-8");
}
$result .= $char;
}
return $result;
}

No comments:

Post a Comment