views:

96

answers:

3

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.

+3  A: 

You could use regular expressions, but it's probably easiest to split it up into an array and operate on each entry:

function fix_entry($str) {
    return ucfirst(ltrim($str));
}

$str = 'john,joy, anna, Lucy bravo,boy';
$fixed = implode(',', array_map(fix_entry, explode(',', $str)));

If you're opposed to making a function you could just use two array_maps, but that's up to you

Michael Mrozek
+2  A: 

Use str_getcsv to break the line into an array. Loop the array and use trim() or ltrim() and ucfirst() on each value.

http://us.php.net/manual/en/function.str-getcsv.php

http://us.php.net/manual/en/function.trim.php

http://us.php.net/manual/en/function.ltrim.php

http://us.php.net/manual/en/function.ucfirst.php

Scott Saunders
+2  A: 

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);
}
John Conde