-2

I have some text that I need each first letter capitalized. But some words are in all caps and I want those words ignored.

$foo = 'product manufacturer for CAMERON TRAILERS';
$foo = ucwords($foo); 

I need this to output as follows:

Product Manufacturer For CAMERON TRAILERS.

Is this possible?

Mike
  • 105
  • 12

2 Answers2

1

On second thought, since neither ucfirst nor ucwords ever translates an uppercase character to its lowercase counterpart; ucwords should be fine for this case. I've changed the function below, so that it will make it more normative though, which would be necessary depending on how you interpret the question.


You'll need to define your own function to do this; PHP has no function with this behavior in its standard library (see note above).

// Let's create a function, so we can reuse the logic
function sentence_case($str){
    // Let's split our string into an array of words
    $words = explode(' ', $str);
    foreach($words as &$word){
        // Let's check if the word is uppercase; if so, ignore it
        if($word == strtoupper($word)){
            continue;
        }
        // Otherwise, let's make the first character uppercase
        $word = ucfirst(strtolower($word));
    }
    // Join the individual words back into a string
    return implode(' ', $words);
}

echo sentence_case('product manufacturer for CAMERON TRAILERS');
// "Product Manufacturer For CAMERON TRAILERS"
Jacob Budin
  • 9,753
  • 4
  • 32
  • 35
  • That worked perfectly. Thank you very much. I appreciate everyones help and patience. – Mike Dec 28 '13 at 05:21
  • The answer above, doesn't work if the sentence is Unicode. I improved the answer as follows `function sentence_case($str){ $words = explode(' ', $str); foreach($words as &$word){ if($word == mb_convert_case($word, MB_CASE_UPPER, "UTF-8")){ continue; } $word = mb_convert_case($word, MB_CASE_TITLE , "UTF-8"); } return implode(' ', $words); } //echo sentence_case('tuyển nhân viên bán hàng trên sàn MTĐT'); // "Tuyển Nhân Viên Bán Hàng Trên Sàn MTĐT"` – Hoàng Vũ Tgtt Sep 15 '22 at 06:43
0

Use this code when you expect like thisProduct Manufacturer For Cameron Trailers

$foo = 'product manufacturer for CAMERON TRAILERS';
echo $foo = ucwords(strtolower($foo));

Look at here http://www.php.net/manual/pt_BR/function.ucwords.php. ucwords not transilating upperletter words

<?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>
Sibiraj PR
  • 1,481
  • 1
  • 10
  • 25