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

How to Explode a String on the Last Delimiter Occurrence?

Linda Hamilton
Release: 2024-10-21 15:19:02
Original
424 people have browsed it

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';
Copy after login

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';
Copy after login

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)));
Copy after login

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',
)
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template