I have a form field called 'Name' - but I'd like to save the submission into the DB as First Name & Last Name using a preg expression.
Can some illustrate how if I entered the name 'John Smith' into the field a regexp would strip this into First Name - John Surname - Smith
Thanks in advance
Prefer use split
(version php < 5.3.0) or explode
which is an alias of split
function, in your case, you just have to split you fullname with space character ' '
var $fullname = "John Smith";
var $splitfullname = $fullname.split(' ');
var $firstname = $splitfullname[0];
var $lastname = $splitfullname[1];
-
var $fullname = "John Smith";
var $splitfullname = explode(' ', $fullname);
var $firstname = $splitfullname[0];
var $lastname = $splitfullname[1];
if you build the form that catch firstname and fullname, I will suggest you to split your fullname input field into two input field (firstname and lastname).
For simple cases, you might just want to split the name by blanks:
$name = "John Smith";
$nameParts = explode(' ',$name);
var_dump($nameParts);
More complex cases (e.g. titles/middle names) might force you to use multiple input fields.
$names = explode(" ", $POST['name']);
$firstName = $name[0];
$lastName = $name[1];
This is however an absolutely brutal idea. Just make a first name and last name form field. I guarantee at some point someone is going to put something like Alfred E Newman and you're going to end up with their initial or middle name as a last name.
Use explode
:
<?php
$fullname='John Smith';
list ($firstName,$lastName)=explode(' ',$fullname);
echo 'First name: '.$firstName.PHP_EOL;
echo 'Last name: '.$lastName.PHP_EOL;
Just created this function just in case someone else has a similar problem - thanks for all of the advice guys!