?
Solved

Remove everything after the first space

Posted on 2006-04-25
4
Medium Priority
?
549 Views
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?
0
Comment
Question by:delarocha
  • 2
4 Comments
 
LVL 49

Expert Comment

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

-r-
0
 
LVL 3

Expert Comment

by:dancablam
ID: 16537296
Hi there. Try this:


<?
$name = "John Smith";

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

Accepted Solution

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

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

-r-
0
 

Author Comment

by:delarocha
ID: 16537344
Roonaan: Perfect! Thank you kindly.
0

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