You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel技术问题:提取字符串大写字母及处理生日查询结果

Laravel 相关问题解答

1. 遍历字符串,仅筛选大写字母并保留空格

可以通过集合结合字符筛选实现,自定义函数处理如下:

function filterUppercaseWithSpaces(string $input): string
{
    return collect(str_split($input))
        ->filter(fn($char) => ctype_upper($char) || $char === ' ')
        ->implode('');
}

// 使用示例
$testStr = "Laravel FRAMEWORK 2024!";
$filtered = filterUppercaseWithSpaces($testStr);
// 输出结果: "FRAMEWORK "

原理:把字符串拆分为单个字符的集合,筛选出符合条件的大写字母或空格,最后拼接成新字符串。

2. 查询今日生日用户并提取纯大写姓名

先优化查询代码(移除无用变量、简化条件),再提取并确保姓名为纯大写格式:

优化后的查询代码

public function handle()
{
    $today = now();
    // 查询今日生日的用户
    $birthdayUsers = Users::select('name', 'primer_apellido', 'segundo_apellido')
        ->whereMonth('fecha_nacimiento', $today->month)
        ->whereDay('fecha_nacimiento', $today->day)
        ->get();

    // 提取并转为纯大写的姓名(可选择合并全名或仅取name字段)
    $uppercaseFullNames = $birthdayUsers->map(function ($user) {
        // 合并全名并去首尾空格后转大写
        return strtoupper(trim("{$user->name} {$user->primer_apellido} {$user->segundo_apellido}"));
        // 若仅需name字段的纯大写,替换为:
        // return strtoupper($user->name);
    });

    // 输出JSON格式结果
    error_log($uppercaseFullNames->toJson());
}

说明

  • 你的原查询返回的JSON中name已是大写,但用strtoupper可确保即使数据库存在非大写数据,最终输出也是纯大写格式。
  • 避免直接用索引(如$nombre_cumple[9])访问集合元素,易触发数组越界错误,推荐用集合遍历方法或$birthdayUsers->get(9)这类安全访问方式。
  • 原代码中$date和$fechahoy变量未使用,可直接删除简化代码。

内容的提问来源于stack exchange,提问作者Vanessa Carrillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 13:18:04