1

I found an answer here: How to capitalize first letter of first word in a sentence? however, it doesn't work when the sentence starts with characters such as " or «.

The code found in the link above is:

$output = preg_replace('/([.!?])\s*(\w)/e', "strtoupper('\\1 \\2')", ucfirst(strtolower($input)));

Here's an example of the handling I need

$input  => «the first article title» 
$output => «The first article title»

$input  => « the first article title »
$output => « The first article title »

$input  => "être"
$output => "Étre"

The idea is to ignore any non alphabetic (not in [a-z, A-Z] + french characters) and apply to the first alphabetic one and the rest will remain the same as the input.

Community
  • 1
  • 1
yazuk
  • 107
  • 1
  • 1
  • 9

1 Answers1

1

Apply a limit so that only 1 character is replaced:

$output = preg_replace('/[a-z]/e', 'strtoupper("$0")', strtolower($input), 1);

Though you should be using preg_replace_callback() rather than the /e switch nowadays:

$output = preg_replace_callback(
    '/[a-z]/',
    function($matches) { return strtoupper($matches[0]); },
    strtolower($string),
    1
);

EDIT

After the scope creep of changing the question to require UTF8 handling:

$output = preg_replace_callback(
    '/\p{L}/u',
    function($matches) { return mb_strtoupper($matches[0]); },
    mb_strtolower($string),
    1
);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Hi, it works fine when it's not french characters. For example "être" as an input will output "êTre". – yazuk Dec 28 '16 at 22:55
  • You have to love scope creep; you never mentioned non-ASCII characters in your original question – Mark Baker Dec 28 '16 at 23:19
  • Hi, it returns empty string :-( – yazuk Dec 28 '16 at 23:32
  • [It works perfectly well with all of your examples](https://3v4l.org/80FQK) – Mark Baker Dec 28 '16 at 23:41
  • I can see, I am using php 5.3 that's why is not working. Please, any idea – yazuk Dec 28 '16 at 23:58
  • Upgrade your PHP to a supported version: PHP5.3 has been end of life since 14 Aug 2014, and even PHP5.6 will only be supported for security patches after tomorrow – Mark Baker Dec 29 '16 at 00:03
  • Hi, Mark, thanks for your help. Is there any way to work this out when it xhtml. I think that's what it causing the problem with **'/\p{L}/u'**. – yazuk Dec 30 '16 at 15:18