...

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



darrensw
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

$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

tangoforce
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.

kbluhm
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 );



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum