Search code examples
phpexplode

Explode string on the last occurrence of character


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!


Solution

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