简体   繁体   中英

Capitalize first letter of a string (preceded with special characters) - PHP

I'd like to capitalize a string like:

¿"hello"?

I want my function to return

¿"Hello"?

I've tried with regex and preg_match, with no luck... Here it is my previous question, related with this one: "preg_match is matching two characters when it should only match one"

Thank you all!

Using preg_replace_callback as said ascii-time above, but unicode compatible:

echo preg_replace_callback('/^(\PL*)(\pL)/u', function($matches){
    return $matches[1] . mb_strtoupper($matches[2],'UTF-8');
}, '¿"éllo"?'),"\n";

output:

¿"Éllo"?

You can do it using preg_replace_callback :

preg_replace_callback('/^([^a-z]*)([a-z])/i', function($matches){
    return $matches[1] . strtoupper($matches[2]);
}, '¿"hello"?');

// ¿"Hello"?

Try ucfirst function http://php.net/manual/en/function.ucfirst.php

No regex is needed for such task

Sample

$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM