【问题标题】:how to use php explode in laravel?如何在laravel中使用php爆炸?
【发布时间】:2018-08-29 13:03:15
【问题描述】:
 $user = $this->user;
            $user->name = $request['name'];
            $user->email = $request['email'];
            $user->password = $request['password'];
            $user->save();

$name = explode(' ' ,$user->name);

$profile= $user->userdetail()->create([
                'user_id' => $request->input('id'),
                'first_name' => <the value of the first exploded string>
'last_name' => the value of the secondexploded string
                ]);

            return redirect('confirmation');
        }

如何在php中使用explode函数拆分两个单词?例如,我注册了 JOhn doe 的名称,我想在我的 userdetail 表中创建 john 的 first_name 和 doe 的 last_name。我该怎么做/

【问题讨论】:

标签: laravel


【解决方案1】:

explode() 返回一个字符串数组,因此您可以使用键访问元素:

$profile = $user->userdetail()->create([
              'user_id' => $request->input('id'),
              'first_name' => $name[0],
              'last_name' => $name[1]
          ]);

【讨论】:

  • 如果用户输入了 Antonio da Silva 这样的名字怎么办?那是三个字,我要怎么循环?
  • 如果用户输入了 Antonio da Silva 这样的名字怎么办?那是三个字,我要怎么循环?
【解决方案2】:

您可以使用以下代码

$full_name = "John Doe";
$name = explode(' ',$full_name);
$first_name = $name[0];
$last_name = $name[1];

【讨论】:

    【解决方案3】:

    另一种方式:

    <?php
    
       $ip = "fname lname"; 
       $iparr = preg_split("/[\s,]+/",$ip); 
       echo "$iparr[0]";
       echo "$iparr[1]";
    
    ?>
    

    但 explode 比 preg_split 好(更快)。 ;)

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多