Jump to content

Break up string into two when there is a space.


Orionsbelter

Recommended Posts

Hi there i stuck and wondering it is is possible to break up a string into two where there is a space for example

 

$fullName="John Doe";

 

i wish to break the string up into

 

$firstName="John";

$lastName="Doe";

 

I need the script to break the two names up from the space it can not contain the space such as

 

$firstName="John ";

$lastName=" Doe";

 

It must split it in two and remove that white space.

 

Pleas help me i'm sure it must be able to do this.

explode() splits string into peaces by seperator implode() joins array of string/nums into one string by given glue.

If u ineterested what list does read about it in manual.

 

I could do it the same with this, but a bit more code is required

$person_data =  explode(" ", $str);
$first = $person_data[0];
$last = $person_data[1];

Depending on how restricted the input is, you'll probably want to use the limit parameter for explode as well:

 

// Limit to two parts so "John Smith Jnr" becomes "John" and "Smith Jnr"
list($first, $last) = explode(" ", $fullName, 2);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.