Remove everything after the first space

Posted on 2006-04-25
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
    LVL 49

    Expert Comment

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

    LVL 3

    Expert Comment

    Hi there. Try this:

    $name = "John Smith";

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

    Accepted Solution

    If you insist on regular expression use:

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


    Author Comment

    Roonaan: Perfect! Thank you kindly.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Enabling OSINT in Activity Based Intelligence

    Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

    As this topic comes over and over again in different forms, I've finally decided to write a short (yea, right...) article / tutorial about pagination with PHP with MySQL database. There are dozens of these kind of tutorials, I know - I wanted to mak…
    Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
    Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

    779 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

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now