views:

219

answers:

5

I'm trying to find a way to break a string at the second last comma, for example:

piece 1, piece 2, piece 3, piece 4, piece 5, piece 6, piece 7 should be 2 parts:

piece 1, piece 2, piece 3, piece 4, piece 5 and

piece 6, piece 7

and

piece 1, piece 2, piece 3, piece 4, piece 5 should be:

piece 1, piece 2, piece 3 and

piece 4, piece 5

Is there a string manipulation to search the string for a character and identify the position of the second last instance of that character?

I thought about exploding the string by , then gluing the last 2 to make part 2, and gluing however many first ones (varies) to make part 1, but I think that might be overkill. Any string manipulations for this?

+3  A: 

Use strrpos to find the position of the last comma.

Use strrpos with the last position as the offset to find the 2nd last comma.

Break the string with substr.

KennyTM
A: 

Regex is a overkill here, you can easily use strpos and substr as mentioned by Kenny. But here is a regex basesd solution:

if(preg_match('{^(.*),(.*?),(.*?)$}',$input,$matches)) {
  $part1 = $matches[1];
  $part2 = $matches[2].','.$matches[3];
}
codaddict
A: 

Even though I agree with codaddict that regular expressions probably isn't really needed, heres more:

For the first n-2 items, replace ',[^,]+,[^,]+$' with '' in the string

For for last 2 items, find the match of '[^,]+,[^,]+$' in the string

Ledhund
A: 
echo preg_replace('~,\s*(?=[^,]*,[^,]*$)~', ",\n", $str)

regular expressions is a tool specifically designed for problems like this, and there's no single reason not to use them. strpos() and friends are just so stupid and verbose...

stereofrog
or $parts = preg_split('~,\s*(?=[^,]*,[^,]*$)~', $str);, depending on what OP means with 'break a string'
Ledhund
A: 

why do you think its overkill using array_splice()?

$string="piece 1, piece 2, piece 3, piece 4, piece 5, piece 6, piece 7";
$s = explode(",",$string);
$t=array_slice($s, 0,-2);
$e=array_slice($s,-2);
print_r($t);
print_r($e);
ghostdog74