I\'d like to capitalize the first letter of a string which could have special characters (that\'s the reason ucfirst is not valid here). I have next code:
$string
This is because your a-z
will not match é. Writing a regex to encompass unicode characters may be difficult.
From your code it will only capitalise the first letter, regardless of the amount of words in your string. If so just do this:
$string = 'ésta';
$ucstring = ucphrase($string);
function ucphrase($word) {
return mb_strtoupper(mb_substr($word, 0, 1)) . mb_substr($word, 1);
}
The mb_*
functions should handle your special characters correctly.
Based on your comment below I understand your dilemma. In that case you can use your regular expression but with the correct unicode selectors
$string = 'ésta';
$pattern = '/(\p{L})(.+)/iu';
$callback_fn = 'process';
echo preg_replace_callback($pattern, $callback_fn, $string);
function process($matches){
return mb_strtoupper($matches[1], 'UTF-8') . $matches[2];
}