删除 ',' 后面的所有空格并使用 PHP 将 CSV 中的第一个字母变为大写

发布于 2024-09-07 12:31:10 字数 259 浏览 3 评论 0原文

我有一个这样的 CSV。

john,joy, anna, Lucy Bravo,boy

我想删除“,”后面的空格(如果存在)。并且将“,”之后的第一个字母设为大写字母(如果它还不是大写的话)。也就是说,它应该是这样的:

John,Joy,Anna,Lucy Bravo,Boy

只有“,”后面的空格应该消失。我自己尝试过。但一切都失败了。我希望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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

朦胧时间 2024-09-14 12:31:10

您可以使用正则表达式,但最简单的方法可能是将其拆分为一个数组并对每个条目进行操作:

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

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

如果您反对创建一个函数,您可以只使用两个 array_map,但仅此而已给你

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

琉璃梦幻 2024-09-14 12:31:10

使用 trim()ucfirst()

这是文档中的修改示例:

$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);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文