Search code examples
phpuppercaselowercase

Check if a word has multiple uppercases letters and only change the words who have One and only uppercase (and be the first letter )


My code so far:

$text = 'Herman Archer LIVEs in neW YORK';
$oldWords = explode(' ', $text);

$newWords = array();

$counter = 0;

foreach ($oldWords as $word) {
    for($k=0;$k<strlen($word);$k++)
        $counter = 0;
        if ($word[k] == strtoupper($word[$k]))
            $counter=$counter+1;
        if($counter>1)
                  $word = strtolower($word);
        if($counter == 1)
                $word = ucfirst(strtolower($word));
           else $word = strtolower($word);

echo $word."<br>";
}

Result:

Herman
Archer
Lives
In
New
York

Expected output:

Herman Archer lives in new york


Solution

  • If you want to use the counter approach you could use something as the following

    <?php
     
    $text = 'Herman Archer LIVEs in A neW YORK';
    $words = explode(' ', $text);
     
    foreach($words as &$word) {
        $counter = 0;
        for($i = 1; $i <= strlen($word);$i++) {
            if (strtoupper($word[$i]) == $word[$i]) $counter++;
            if ($counter == 2) break;
        }
        if ($counter == 2) $word = strtolower($word);
    }
    echo implode(' ', $words);