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>
Output:
<code class="php">array ( 0 => 'and more', 1 => 'string', 2 => 'this is my', )</code>
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!