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

how to split two words using explode function in php? For example i registered wth name of JOhn doe I want to create in my userdetail table the first_name of john and last_name of doe. How can i do it/

2
  • Possible duplicate of PHP explode function Commented Feb 3, 2017 at 7:08
  • Other answers are exact Commented Feb 3, 2017 at 7:40

3 Answers 3

6

explode() returns an array of strings, so you can access elements by using keys:

$profile = $user->userdetail()->create([
              'user_id' => $request->input('id'),
              'first_name' => $name[0],
              'last_name' => $name[1]
          ]);
Sign up to request clarification or add additional context in comments.

2 Comments

What if the user inputs a name like Antonio da Silva ? that is 3 words how am i gonna loop through that ?
What if the user inputs a name like Antonio da Silva ? that is 3 words how am i gonna loop through that ?
6

You can use the following code

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

Comments

0

Alternate way :

<?php

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

?>

But explode is good(faster) than preg_split. ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.