1

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 = 'ésta';
$pattern = '/^([^a-z]*)([a-z])/i';

$callback_fn = 'process';

echo preg_replace_callback($pattern, $callback_fn, $string);


function process($matches){
    return $matches[1].strtoupper($matches[2]);
}

which returns 'éSta' but 'Ésta' was expected... I think my problem is the pattern I'm using, but I have made different combinations (like $pattern = '/\pL/u') but I haven't found a good regex.

1 Answer 1

2

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

My problem is that it's not always the first letter wich I have to capitalize, because my string could be something like '¿"ésta"?' and I want my function to return '¿"Ésta"?'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.