Codex73
Codex73

Reputation: 5766

Split string in half by a delimiting substring

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

Upvotes: 1

Views: 7723

Answers (4)

singpolyma
singpolyma

Reputation: 11241

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

Upvotes: 0

Chad Birch
Chad Birch

Reputation: 74518

$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];

Upvotes: 6

Keith Gaughan
Keith Gaughan

Reputation: 22675

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

Upvotes: 1

Megra
Megra

Reputation:

$parts = explode ($split_point, $string);
/*
$parts[0] = 'This is string sample'
$parts[1] = '$2565'
*/

Upvotes: 1

Related Questions