#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2011
    Posts
    11
    Rep Power
    0

    Help needed to remove last portion of a string


    I'm a total n00b to regex and I have been working for hours on this and cannot get anything to work as I'd like.

    I need to remove the last part of a string that occurs after (and including):
    Code:
    _x_
    The remaining characters are all lower case and underscores.

    eg.

    elaphe_guttata_x_elaphe_guttata_emoryi

    needs to be:
    elaphe_guttata

    My first thoughts are to use preg_replace() with an empty string for the replace part but really struggling with the expression to use. Any help is greatly appreciated
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,988
    Rep Power
    9397
    PHP? You don't need regular expressions: find the offset of the "_x_" and (if it is in fact in there) then only keep everything up to it.
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2012
    Location
    spaceBAR Central
    Posts
    229
    Rep Power
    42
    This is one way:
    Code:
    $test = "elaphe_guttata_x_elaphe_guttata_emoryi";
    $test = preg_replace('/(.+)_x_.*/', '\1', $test);
    echo $test;
    elaphe_guttata
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2011
    Posts
    11
    Rep Power
    0
    thanks requinix, I didn't think of that, it worked like a charm

IMN logo majestic logo threadwatch logo seochat tools logo