2

I need a function that capitalizes first letter (not a symbol/character) of each word. In this case I would like to use some custom function similar to ucwords().

For example, this works perfectly:

// returns: This Works Perfectly
ucwords( 'this works perfectly' );

But this one fails:

// returns: This Works Perfectly (or "maybe Not" Always)
// i want a function which returns: This Works Perfectly (Or "Maybe Not" Always)
ucwords( 'this works perfectly (or "maybe not" always)' );

The thing is that

(or

and

"maybe

are not capitalised, but I need it to be capitalised. Does someone have a custom function for that?

Thank you in advance!

E. Mure
  • 21
  • 1
  • You could write one yourself, and this would be a perfect exercise for TDD. So, what have you tried so far? – Nico Haase Dec 18 '18 at 10:21

2 Answers2

0

Since PHP version 5.5.16, the function ucwords has the second parameter named $delimiters, that it's default values are " \t\r\n\f\v", as you can see in the official docs: http://php.net/manual/en/function.ucwords.php

You can try like that:

$delimiters = " \t\r\n\f\v\"'()"    
ucwords( 'this works perfectly (or "maybe not" always)', $delimiters );
0

Finally, I've found the proper solution to support any letter character

<?php
echo preg_replace_callback('/(?<=\s|^|\W|\d)([\p{L}])/u', function($match) {
    return mb_strtoupper($match[1]);
}, 'this works perfectly (or "maybe not" always)');
Rulisp
  • 1,586
  • 1
  • 18
  • 30