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

放肆的年华 提交于 2019-12-21 17:45:10

问题


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!


回答1:


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"?



回答2:


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"?



回答3:


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!


来源:https://stackoverflow.com/questions/11122274/capitalize-first-letter-of-a-string-preceded-with-special-characters-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!