user1833552
user1833552

Reputation:

Convert a string to lower case only if the first letter isn't a upper case

So I have to make web page that contains a text area (words devided by spaces) that can be filled out.

As a result every word out of the text (one word per line) has to be shown on screen, in which every word the uppercase is transformed to a lower case, except if the first letter of the word in process is a upper case.

Example: ''tHIs is the StacKOverFlOW SiTE'' would be ''this is the Stackoverflow Site"

I know I have to work with explode(), strotoupper() and strotolower() I just can't get the code working.

Upvotes: 0

Views: 952

Answers (3)

rojoca
rojoca

Reputation: 11190

function lower_tail($str) {
    return $str[0].strtolower(substr($str, 1));
}

$sentence = "tHIs is the StacKOverFlOW SiTE";
$new_sentence = implode(' ', array_map('lower_tail', explode(' ', $sentence)));

UPDATE:

Here is a better version that handles some other situations:

$sentence = "Is tHIs, the StacKOverFlOW SiTE?\n(I doN'T know) [A.C.R.O.N.Y.M] 3AM";
$new_sentence = preg_replace_callback(
    "/(?<=\b\w)(['\w]+)/",
    function($matches) { return strtolower($matches[1]); },
    $sentence);
echo $new_sentence; 
// Is this, the Stackoverflow Site?
// (I don't know) [A.C.R.O.N.Y.M] 3am
// OUTPUT OF OLD VERSION:
// Is this, the Stackoverflow Site?
// (i don't know) [a.c.r.o.n.y.m] 3am

(Note: PHP 5.3+)

Upvotes: 2

Gar
Gar

Reputation: 862

i'd write it this way

$tabtext=explode(' ',$yourtext);
foreach($tabtext as $k=>$v)
{
    $tabtext[$k]=substr($v,0,1).strtolower(substr($v,1));
}
$yourtext=implode(' ',$tabtext);

Upvotes: 0

TheWolf
TheWolf

Reputation: 1385

$text = 'tHIs is the StacKOverFlOW SiTE';
$oldWords = explode(' ', $text);
$newWords = array();

foreach ($oldWords as $word) {
    if ($word[0] == strtoupper($word[0])
        $word = ucfirst(strtolower($word));
    else
        $word = strtolower($word);

    $newWords[] = $word;
}

Upvotes: 1

Related Questions