Reg exp to remove all spaces prior to start of phrase which itself has spaces??

Discussion in 'PHP' started by carlos123, Oct 28, 2009.

  1. #1
    I have spent hours and hours on this (it's part of a much larger application) and just can't get past the test code snippet below. I would really appreciate a second set of eyes on this.

    For purposes of what I am trying to accomplish I am trying to remove all spaces other than the one that appears between the name of "Joe Smith".

    The problem is that the regular expression on the right of the equal sign ends up capturing the last space before the first character in the name "Joe Smith". Not what I want. I want ALL spaces removed other than any spaces after the first character of any value assigned to MyName.

    In other words the reg exp should capture "MyName" and "Joe Smith" into the matches array. No spaces other than any after the first character of "J".

    Anybody got any ideas?

    Thanks.

    Carlos
     
    carlos123, Oct 28, 2009 IP
  2. kbluhm

    kbluhm Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    No need for regex in this case, unless there is more to it that you are not telling:
    
    $text = "MyName = Joe Smith\n";
    
    $matches = explode( '=', $text );
    
    $matches = array_map( 'trim', $matches );
    
    PHP:
     
    kbluhm, Oct 28, 2009 IP
  3. carlos123

    carlos123 Peon

    Messages:
    58
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    That's very interesting kbluhm. Do you happen to know off the top of your head if your solution is faster than using a regular expression?

    By the way I believe that if I add a "?" to the second "\s*" that it also works but your solution is definitely cleaner if it is indeed faster.

    Carlos
     
    carlos123, Oct 28, 2009 IP
  4. hugsbunny

    hugsbunny Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    it's alot faster
     
    hugsbunny, Mar 21, 2010 IP