Home > Backend Development > PHP Tutorial > How to Split a String at the Last Occurrence of a Delimiter?

How to Split a String at the Last Occurrence of a Delimiter?

Barbara Streisand
Release: 2024-10-21 15:21:30
Original
522 people have browsed it

How to Split a String at the Last Occurrence of a Delimiter?

Splitting a String on the Last Occurrence of a Delimiter

When splitting a string based on a specified delimiter, the default behavior is to separate the string into elements at each occurrence of the delimiter. However, there may be scenarios where you need to consider only the last occurrence of the delimiter, ignoring any others.

To achieve this right-to-left split, one approach is to leverage the strrev function. By reversing the original string and the delimiter, you can effectively reverse the search pattern.

Solution:

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

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

// Reverse the reversed result to obtain the desired output
$result = array_map('strrev', $reversed_result);</code>
Copy after login

Output:

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

This technique allows you to split the string based on the last occurrence of the delimiter, achieving the desired element division. Although other solutions may exist, this approach provides a straightforward and effective way to handle this specific scenario.

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