function to change text to sentence case

Discussion in 'PHP' started by monkeyclap, Feb 19, 2010.

  1. #1
    hi, i have the following code:

    function sentence_case($string) {
        $sentences = preg_split('/([.?!\r\n]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
        $new_string = '';
        foreach ($sentences as $key => $sentence) {
            $new_string .= ($key & 1) == 0?
                ucfirst(strtolower(trim($sentence))) :
                $sentence.' ';
        }
        return trim($new_string);
    }
    PHP:
    the above works fine but the issue is with text on new lines. a space is inserted in front of the first word. is it possible to remove this space? thanks
     
    monkeyclap, Feb 19, 2010 IP
  2. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #2
    function sentence_case($string) {
        $sentences = preg_split('/([.?!\r\n]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
        $new_string = '';
    
        foreach ($sentences as $key => $sentence)
        {
            $new_string .= ($key % 2 == 0)?
                ucfirst(strtolower(trim($sentence))) :
                $sentence;
        }
        return trim($new_string);
    }
    PHP:
     
    wmtips, Feb 19, 2010 IP
  3. monkeyclap

    monkeyclap Active Member

    Messages:
    836
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    85
    #3
    hmmm, now that removes all spaces after punctuation... which again is not what's needed. i think it's very close close, any ideas? cheers
     
    monkeyclap, Feb 19, 2010 IP
  4. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #4
    You are right, a little correction:

    function sentence_case($string) {
        $sentences = preg_split('/([.?!\s]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
        $new_string = '';
    
        foreach ($sentences as $key => $sentence)
        {
            $new_string .= ($key % 2 == 0)?
                ucfirst(strtolower(trim($sentence))) :
                $sentence;
        }
        return trim($new_string);
    }
    PHP:
     
    wmtips, Feb 19, 2010 IP
    monkeyclap likes this.
  5. monkeyclap

    monkeyclap Active Member

    Messages:
    836
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    85
    #5
    now that just seems to be doing a ucwords on the text?
     
    Last edited: Feb 19, 2010
    monkeyclap, Feb 19, 2010 IP