0

This is my code, currently I am able to break it into two variable successfully

$string="life really";
list($firstName, $lastName) = explode(" ", $string);
echo $firstName;  
echo $lastName;  

the output will be like

life
really

This is my second try

$string="life really suck";
list($firstName, $lastName) = explode(" ", $string);
echo $firstName;  
echo $lastName;  

it only echo first and last word in the string

which is life and suck, it didn't capture "really suck" in the $lastname

What I wanted to do is, I want to capture the first word in the $firstname and capture the whatever after the first spacing and place in the $lastname.

Is it possible?

2
  • 1
    Why are you using list() ? Commented Jul 24, 2013 at 12:30
  • @SkarXa IMHO this is a perfectly good example of using function list Commented Jul 24, 2013 at 13:22

4 Answers 4

4

According to the PHP manual, explode has an optional third parameter that specifies a limit for how many elements the function can return. Using this limit, you can make the function put the first match in the first element and the rest of the string in the second element.

Example:

$string="life really suck";
list($firstName, $lastName) = explode(" ", $string, 2); // Added argument 2
echo $firstName;
echo $lastName;

http://ideone.com/Vu0GUz

Sign up to request clarification or add additional context in comments.

Comments

1

This provides a correct solution: given a string like "A B C D ..." will return 2 variables:

$v1 = "A"; $v2 = "B C D ...";

here's the code.

$string="life really suck a lot";
$parts = explode(" ", $string);
$v1 = array_shift($parts);
$v2 = implode(" ", $parts);

output:

$v1 = "life"

$v2 = "really suck a lot";

3 Comments

I would use $v1 = array_shift($parts);
@HeinAndréGrønnestad thanks, i didn't know that function before now
"life really suck a lot" :D
0

Try this :

$string="life really suck";
preg_match("/(?P<firstname>\w+) (?P<lastname>.*)/",$string,$match);

extract($match);
echo $firstname;
echo "<br>";
echo $lastname;

3 Comments

Wow, a regex! nice but overkill :D (PS: I'm a fan of the saying "There's no such thing as too much firepower", anyway)
@STTLCU : I think regex is better option than explode, and it is simple regex
Regex is not meant to be simple, but to be mighty. Ergo regex is never simple!
0

Try this.

<?php
    $string="life really suck";
    list($firstName, $middlename, $lastName) = explode(" ", $string);
    echo $firstName; 
    echo $middlename;   
    echo $lastName;  
?>

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.