0

I am using php 7.4 and I have the following string:

Tester Test Street 11 (Nursing Home, Example), 1120 New York
                                             '-------------Split String here 
                                   '-----------------------NOT HERE   

When I do explode() I get:

$addressAll = explode(", ", "Tester Test Street 11 (Nursing Home, Example), 1120 New York");

/*
array(3) {
  [0]=>
  string "Tester Test Street 11 (Nursing Home"
  [1]=>
  string "Example)"
  [2]=>
  string "1120 New York"
}
*/

However, I would like to get:

array(3) {
  [0]=>
  string "Tester Test Street 11 (Nursing Home, Example)"
  [1]=>
  string "1120 New York"
}

Any suggestions how to only split the last occurrence of ,.

I appreciate your replies!

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • 1
    Does this answer your question? [Explode only by last delimiter](https://stackoverflow.com/questions/16610791/explode-only-by-last-delimiter) – El_Vanja Apr 09 '21 at 16:50
  • If `explode()` does not do what you need then don't use `explode()`. Or use it and process the value it returns to achieve your goal, don't expect it to do what it was not designed to do. – axiac Apr 09 '21 at 17:11

2 Answers2

2

Use strrpos() to find the position of the last comma in the input string and substr() to extract the substrings located after befora and after the last comma:

$input = 'Tester Test Street 11 (Nursing Home, Example), 1120 New York';
$pos = strrpos($input, ',');
$prefix = substr($input, 0, $pos);
$suffix = substr($input, $pos + 1);

See it in action.

axiac
  • 68,258
  • 9
  • 99
  • 134
1

A solution with preg_split(). The string is separated by a single comma, which is only followed by characters without a comma up to the end of the character string.

$input = 'Tester Test Street 11 (Nursing Home, Example), 1120 New York';

$array = preg_split('~,(?=[^,]+$)~',$input);

?= causes the expression in brackets not to be used as a back reference.

jspit
  • 7,276
  • 1
  • 9
  • 17