View Full Version : Find first instance of character, then stop at space?

01-24-2012, 07:10 AM
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


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

01-24-2012, 12:45 PM
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.

01-24-2012, 03:48 PM
Untested, but should work:

$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', $sentence, NULL, PREG_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 );