Home  >  Article  >  Backend Development  >  How to Perform a Right-to-Left Split on the Last Delimiter Instance in a String?

How to Perform a Right-to-Left Split on the Last Delimiter Instance in a String?

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 15:24:02785browse

How to Perform a Right-to-Left Split on the Last Delimiter Instance in a String?

Exploding on the Last Delimiter Instance: A Right-to-Left Approach

The given task is to split a string on a specific delimiter but only consider the last occurrence of that delimiter. While regular string splitting functions like explode() work from left to right, there's a unique way to achieve the desired result.

Consider the following example:

$split_point = ' - ';
$string = 'this is my - string - and more';

The goal is to split the string on the last instance of the "-" delimiter, resulting in an array like:

$item[0] = 'this is my - string';
$item[1] = 'and more';

Instead of using explode() from left to right, we can reverse the string and reverse the resulting array:

$result = array_map('strrev', explode($split_point, strrev($string)));

This approach involves:

  1. Reversing the string ($string) to perform the split from right to left.
  2. Calling explode() on the reversed string to split it on the delimiter.
  3. Mapping strrev() to the resulting array to reverse each element.

The function array_map() is used to apply strrev() to each element in the array. The actual output would be:

array (
  0 => 'and more',
  1 => 'string',
  2 => 'this is my',
)

This technique may not be the most efficient solution, but it effectively achieves the goal of exploding on the last delimiter instance by reversing the string and reversing the result.

The above is the detailed content of How to Perform a Right-to-Left Split on the Last Delimiter Instance in a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn