Jump to content

[SOLVED] probabaly going mad


RobinTibbs

Recommended Posts

ok basically this function is meant to capitalise text properly, so given "HELLO THERE" it should return "Hello There". however what is being returned is "hello there". what am i missing? many thanks. code is probably big mess ^^

 

function prettyfyText($text){
    $text = strtolower($text);
    $explode = explode(" ", $text);
    $i = 0;
    
    while($i < count($explode)) {
        $string = str_split($explode[$i]);
        $idx = 0;
        while($idx<count($string)){
            if($idx == 0) {
                $string[$idx] = strtoupper($string[$idx]);
            }
            $idx++;            
            //echo $string[0]." ".$string[1]."<br />";
            $nice = implode("", $string);
        }
        $blah = implode(" ", $explode);
        
        $i++;
    }    
    echo $blah;
} // end function prettyfyText

Link to comment
https://forums.phpfreaks.com/topic/36950-solved-probabaly-going-mad/
Share on other sites

Robin, obviously Jesirose's answer is the best way to do it as someone has very nicely written the function for you, but if you wanted a better way than your function does it you could have done it this way

<?php
function prettyfyText($text){
    $text = strtolower($text);
    $explode = explode(" ", $text);
    $i = 0;
    $return = ""; //initialise the return sentence   
    while($i < count($explode)) {
        $end = substr($explode[$i],1); //get all the letters after the first one
        $begin = strtoupper(substr($explode[$i],0,1)); // turn to uppercase the first letter of the word
        $newstr = "$begin$end"; //rebuild the word
        $return .= " $newstr"; //concatenate the sentence again
        $i++; //increase the counter
    }   
    return $return; //return the rebuilt sentence
echo prettyfyText("HELLO WORLD HOW ARE YOU"); // Hello World How Are You

 

just because I had done it, not having myself seen the ucwords function before - so thanks from me too Jesi.

Yep, always good to check the manual before trying to write stuff like this. It's often already been done :) A good way to check is to search the manual for similar functions. In this case, you already knew about strtoupper - at the bottom it says

"See also strtolower(), ucfirst(), ucwords() and mb_strtoupper()."

 

It's an easy way to learn about new functions, I find great shortcuts that way all the time.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.