Search code examples
phpcsvwhitespacecapitalizeuppercase

Remove all the whitespace after ',' and make first letter uppercase in CSV with PHP


I'm having a CSV like this.

john,joy, anna, Lucy Bravo,boy

I want to remove whitespace after ',' if it exist. And also make the first letter after ',' to be capital letter, if its not capital already. That is it should be like this:

John,Joy,Anna,Lucy Bravo,Boy

Only the whitespace after the ',' should go. I tried myself. But all failed. I hope PHP can solve this.


Solution

  • Use trim() and ucfirst().

    Here's a modified example from the documentation:

    $row = 1;
    if (($handle = fopen("test.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>\n";
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo ucfirst(trim($data[$c])) . "<br />\n";
            }
        }
        fclose($handle);
    }