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

Barbara Streisand
Release: 2024-10-21 15:24:02
Original
784 people have browsed it

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

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!