Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Mar 2011
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Find first instance of character, then stop at space?

    I think I need to use some kind of regex but struggling...

    I have a string e.g.

    the cat sat of the mate and $10 was all it cost

    I want to return

    $10

    And is there a universal name for currency codes so I could return £10 if it was

    the cat sat of the mate and £10 was all it cost

    Or a way to add more characters to the expression

  • #2
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,341
    Thanks
    60
    Thanked 527 Times in 514 Posts
    Blog Entries
    4
    explode() is probably the function you are looking for. It will break up the sentence by the desired character (in your case the space) and return everything as an array.
    See my new CodingForums Blog: http://www.codingforums.com/blogs/tangoforce/

    Many useful explanations and tips including: Cannot modify headers - already sent, The IE if (isset($_POST['submit'])) bug explained, unexpected T_CONSTANT_ENCAPSED_STRING, debugging tips and much more!

  • #3
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    Untested, but should work:
    PHP Code:
    $sentence 'the cat sat of the mate and $10 was all it cost';

    // Split $sentence into $words on one-or-more spaces
    $words preg_split'/\s+/s'$sentenceNULLPREG_SPLIT_NO_EMPTY );

    // Grab all $words starting with `$` or `£`
    $matches preg_grep'/^[\$£]./'$words );

    // What do we have?
    print_r$matches );

    // First match
    $first reset$matches ); 
    Last edited by kbluhm; 01-25-2012 at 04:36 AM.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •