First word in string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
larrytech
Forum Commoner
Posts: 35
Joined: Thu Jun 06, 2002 8:27 am

First word in string

Post by larrytech »

Hi,
If i have a variable like
$name = "Joe Blogs";
how can I trim it so it just says "Joe". I need these to work for all length not just 3 characters!
Thanks,
Larru
will
Forum Contributor
Posts: 120
Joined: Fri Jun 21, 2002 9:38 am
Location: Memphis, TN

Post by will »

here ya go....

Code: Select all

$name = ereg_replace("\ .*$","",$name);
this will also work if they have more than two names (say a middle name as well)... it will trim it down up to the first space.
larrytech
Forum Commoner
Posts: 35
Joined: Thu Jun 06, 2002 8:27 am

Post by larrytech »

Thanks alot! That's great.
will
Forum Contributor
Posts: 120
Joined: Fri Jun 21, 2002 9:38 am
Location: Memphis, TN

Post by will »

just thought about it.... you might use this instead, so that you could retrieve their last name also if you so choose later...

Code: Select all

$name = 'John Doe';

$nameArray = explode(" ",$name);

//first name
echo $nameArrayї0];

//second name
echo $nameArrayї1];

//etc, etc
only problem you might run into is if their last name is something like St. James.... it would break that apart. for this, you would need to know if they were specifying a middle name or not.
larrytech
Forum Commoner
Posts: 35
Joined: Thu Jun 06, 2002 8:27 am

Post by larrytech »

Great! That is even more useful. Luckily I can't think of many folks with surnames like that :D !
Post Reply