How to use strrev() and strpos() Functions In PHP
Reverse the string with strrev() function and find the position of the first occurrence of the delimiter using strpos() function, and then split the reversed string.
Example:
PHP
<?php $string = "Sam/is/working/hard" ; // Reverse the string $reversedString = strrev ( $string ); // Find the position of the first occurrence of '|' $firstDelimiterPos = strpos ( $reversedString , "/" ); // Split the reversed string based // on the first occurrence of '|' $part1 = substr ( $reversedString , $firstDelimiterPos ); $part2 = substr ( $reversedString , 0, $firstDelimiterPos ); // Reverse each part back to the original order $part1 = strrev ( $part1 ); $part2 = strrev ( $part2 ); echo "String 1: $part1\n" ; echo "String 2: $part2\n" ; ?> |
String 1: Sam/is/working/ String 2: hard
How to Split on Last Occurrence of Delimiter in PHP ?
Given a string, the task is to split the string based on the last occurrence of a delimiter. In this article, we use the delimiter pipe symbol i.e. “|”.
Consider the below example:
Input:
Sam|is|working|hard
Output: String 1: Sam|is|working String 2: hard
There are four approaches to split the string, which are described below:
Table of Content
- Using strrpos() and substr() functions
- Using explode() and implode() functions
- Using Regular Expressions
- Using strrev() and strpos() Functions