Home  >  Article  >  Backend Development  >  How to Explode a String on the Last Delimiter Occurrence?

How to Explode a String on the Last Delimiter Occurrence?

Linda Hamilton
Linda HamiltonOriginal
2024-10-21 15:19:02349browse

How to Explode a String on the Last Delimiter Occurrence?

Exploding Strings on the Last Delimiter Occurrence

In many cases, it becomes necessary to split a string based on a specific delimiter. However, there are situations when we need to consider only the last occurrence of the delimiter.

Problem Statement

Given:

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

To split the string on the last instance of $split_point, we would like to achieve the following result:

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

Solution

To achieve this, we can employ a clever technique using the strrev function to reverse the string and then explode it on the reversed delimiter:

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

By reversing the string, the last instance of the delimiter becomes the first occurrence. After splitting the reversed string, we reverse the result to restore the original order.

Output

This approach produces the desired output:

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

The above is the detailed content of How to Explode a String on the Last Delimiter Occurrence?. 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