jprog
jprog

Reputation: 155

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!

Upvotes: 4

Views: 1246

Answers (3)

Toto
Toto

Reputation: 91518

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

Upvotes: 2

Paul
Paul

Reputation: 141935

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

Upvotes: 1

Ribtoks
Ribtoks

Reputation: 6922

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!

Upvotes: -1

Related Questions