Remove everything after the first space

Posted on 2006-04-25
Medium Priority
Last Modified: 2012-06-21
I'm working in PHP and have a variable set to "firstname lastname". I wish to set a new variable to just the first name, by stripping out the space and anything after it using a regular expression. Can anyone help with the syntax to do so?
Question by:delarocha
  • 2
LVL 49

Expert Comment

ID: 16537275
list($firstname, $everythingelse) = explode(' ', $string, 2);


Expert Comment

ID: 16537296
Hi there. Try this:

$name = "John Smith";

if (preg_match('/[\\w]*/', $name, $regs)) {
      $result = $regs[0];
} else {
      $result = "";
LVL 49

Accepted Solution

Roonaan earned 200 total points
ID: 16537312
If you insist on regular expression use:

$firstname = preg_replace('/^([^ ]+).*/', '\1', $name);


Author Comment

ID: 16537344
Roonaan: Perfect! Thank you kindly.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses
Course of the Month16 days, 23 hours left to enroll

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question