How to Explode Arrays from Right to Left: Splitting on the Last Delimiter in PHP

Susan Sarandon
Release: 2024-10-21 15:24:30
Original
153 people have browsed it

How to Explode Arrays from Right to Left: Splitting on the Last Delimiter in PHP

Exploding Arrays from Right to Left: Last Delimiter Split

In PHP, the explode() function is commonly used for splitting strings based on specified delimiters. However, if you need to split a string only on the last occurrence of a particular delimiter, you may encounter ambiguity.

For instance, consider the following scenario:

<code class="php">$split_point = ' - ';
$string = 'this is my - string - and more';</code>
Copy after login

If you were to use explode() directly on this string, you would get the following result:

<code class="php">$item[0] = 'this is my';
$item[1] = 'string - and more';</code>
Copy after login

However, this is not the desired output because we only want to split on the second instance of the delimiter. To achieve that, we can employ a slightly different approach using the strrev() function.

<code class="php">$split_point = ' - ';
$string = 'this is my - string - and more';

$result = array_map('strrev', explode($split_point, strrev($string)));</code>
Copy after login

Here's how this works:

  1. We first reverse the entire string using strrev().
  2. Then, we perform the explode() operation on the reversed string, effectively splitting it from right to left.
  3. Finally, we apply strrev() again to each element of the resulting array to restore their original order.

This approach yields the following output:

<code class="php">array (
  0 => 'and more',
  1 => 'string',
  2 => 'this is my',
)</code>
Copy after login

By reversing the string and then splitting, we essentially transform the search into a left-to-right operation from the end of the string, allowing us to capture the last instance of the delimiter.

The above is the detailed content of How to Explode Arrays from Right to Left: Splitting on the Last Delimiter in PHP. 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!