How to extract the start of a string

Hi all,

If a form field collects a name into a variable, such as $name = “Fred Smith”, is there a function in PHP—or some easy means—to extract just the first name?

In other words, I’d like to end up with a new variable like $first-name = “Fred”.

As you can tell, PHP is not my area!

Thanks for any suggestions. :slight_smile:

If you can assume the first name is the part of the string before the first space, it would be

$firstname = substr($name, 0, strpos($name, ' '));

If someone has two first names this won’t work of course.
You might be tempted to take every word up until the last space, but that doesn’t work if someone has multiple last names.
This is exactly the reason why I always ask for first name and last name seperately in forms :slight_smile:

You could use explode

But that would only work with simple names. Not with these names:

John John Smith
Jane Smith Jones

Thanks everyone for your quick answers!

Thanks guido. Why do you say it wouldn’t work with those names? I would be happy with extracting “john” and “Jane”, so it looks like it would work for me.

Yes, I realize there is a bit of luck involved with this (it would be funny if someone wrote Mr or Mrs before the name!) but I figure it’s reasonably safe in general. I often collect first and last names separately, but on a current form the client would prefer the whole name in one, so I thought I’d try out this method.

That’s an interesting one.

I’ll give each of these a go. Thanks again, guys!

An easy way to extract everything up to the first space character (which may or may not be a person’s first name) would be:

strtok($name, " ")