phpstringsentencecapitalize

How can I capitalize the first word of each sentence of a string in PHP?


I am trying to capitalize the first letter of every sentence (after a period, ? or !) I can capitalize the first letter of only the first sentence. Can anyone please help?

$content_trimmed = ucfirst(strtolower($content_trimmed));

Solution

  • Try this

    <?php
    function capitalize_sentences($text) {
        // Split the text into sentences using regular expression to match ., !, or ?
        $sentences = preg_split('/([.!?]\s*)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    
        // Loop through the sentences and capitalize the first letter of each
        $result = '';
        foreach ($sentences as $key => $sentence) {
            // If it's an actual sentence (not punctuation), capitalize it
            if ($key % 2 == 0) {
                $result .= ucfirst(strtolower($sentence)); // Capitalize and make the rest lowercase
            } else {
                $result .= $sentence; // Add punctuation back
            }
        }
    
        return $result;
    }
    
    // Example usage
    $text = "hello. how are you? i'm fine! how about you?";
    echo capitalize_sentences($text);
    ?>