How to Split on Last Occurrence of Delimiter in PHP ?
Last Updated :
06 Feb, 2024
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:
Using strrpos() and substr() functions
The strrpos() function is used to find the position of the last occurrence of the delimiter ‘|’. If the delimiter is found ($lastDelimiterPos is not false), substr() function is then used to split the string into two parts based on the position of the last delimiter.
Example:
PHP
<?php
$string = "Sam/is/working/hard" ;
$lastDelimiterPos = strrpos ( $string , '/' );
if ( $lastDelimiterPos !== false) {
$part1 = substr ( $string , 0, $lastDelimiterPos );
$part2 = substr ( $string , $lastDelimiterPos + 1);
echo "String 1: $part1\n" ;
echo "String 2: $part2\n" ;
} else {
echo "Delimiter not found in the string.\n" ;
}
?>
|
Output
String 1: Sam/is/working
String 2: hard
Using explode() and implode() functions
We can reverse the string and use explode() function to split the string based on the first occurrence of the delimiter, and then reverse the resulting array using implode() function.
Example:
PHP
<?php
$string = " Sam/is/working/hard" ;
$reversedString = strrev ( $string );
$parts = explode ( '/' , $reversedString , 2);
$part1 = strrev ( $parts [1]);
$part2 = strrev ( $parts [0]);
echo "String 1: $part1\n" ;
echo "String 2: $part2\n" ;
?>
|
Output
String 1: Sam/is/working
String 2: hard
Using Regular Expressions
Regular expressions can be used to match the last occurrence of the delimiter and split the string accordingly.
Example:
PHP
<?php
$string = "Sam/is/working/hard" ;
preg_match( '/^(.*)\/(.*)$/' , $string , $matches );
$part1 = $matches [1];
$part2 = $matches [2];
echo "String 1: $part1\n" ;
echo "String 2: $part2\n" ;
?>
|
Output
String 1: Sam/is/working
String 2: hard
Using strrev() and strpos() Functions
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" ;
$reversedString = strrev ( $string );
$firstDelimiterPos = strpos ( $reversedString , "/" );
$part1 = substr ( $reversedString , $firstDelimiterPos );
$part2 = substr ( $reversedString , 0, $firstDelimiterPos );
$part1 = strrev ( $part1 );
$part2 = strrev ( $part2 );
echo "String 1: $part1\n" ;
echo "String 2: $part2\n" ;
?>
|
Output
String 1: Sam/is/working/
String 2: hard
Share your thoughts in the comments
Please Login to comment...