views:

4312

answers:

4

Have the following string i need to split.

$string = "This is string sample - $2565";
$split_point = " - ";

One: I need to be able to split the string into two parts using a regex or any other match and specify where is going to split.

Second: Also want to do a preg_match for $ and then only grab number on the right of $.

Any suggestions?

+6  A: 
$split_string = explode($split_point, $string);

and

preg_match('/\$(\d*)/', $split_string[1], $matches);
$amount = $matches[1];

If you want, this could all be done in one regex with:

$pattern = '/^(.*)'.preg_quote($split_point).'\$(\d*)$/'

preg_match($pattern, $string, $matches);
$description = $matches[1];
$amount = $matches[2];
Chad Birch
Please, to avoid unexpected errors, do add preg_quote around the $split_point in the regex example.
Wimmer
+1  A: 
$parts = explode ($split_point, $string);
/*
$parts[0] = 'This is string sample'
$parts[1] = '$2565'
*/
+1  A: 

Two other answers have mentioned explode(), but you can also limit the number of parts it's meant to split your source string into. For instance:

$s = "This is - my - string.";
list($head, $tail) = explode(' - ', $s, 2);
echo "Head is '$head' and tail is '$tail'\n";

Will given you:

Head is 'This is' and tail is 'my - string.'
Keith Gaughan
Isn't the output: Head is 'This is-' and tail is 'my - string.' ?
Codex73
Nope, definitely not. I even checked it in the PHP REPL before posting.
Keith Gaughan
so what happened to the first - ?
Codex73
your completely right. I forgot you exploded " - " and not "-".
Codex73
how will i split from the last - and not the first. can i make explode search from right to left instead?
Codex73
There's no simple way to do that, mainly because it's not something you usually want to do. Unfortunately, the intuitive way of doing it (using a negative number) does something completely different. Try exploding the string, popping the last element, and imploding it again.
Keith Gaughan
A: 

explode is the right solution for your specific case, but preg_split is what you want if you ever need regular expressions for the separator :)

singpolyma