How to Split String by Delimiter/Separator in PHP?
Last Updated :
07 Feb, 2024
Given a String, the task is to split the string by the delimiter. In this case, the delimiter is comma “,”.
Examples:
Input: apple,orange,banana
Output:
apple
orange
banana
There are seven approaches to split the string, these are:
Split String by Delimiter using explode() Function
The explode() function splits a string into an array based on a specified delimiter (in this case, a comma).
PHP
<?php
$string = "apple,orange,banana" ;
$fruitsArray = explode ( ',' , $string );
foreach ( $fruitsArray as $fruit ) {
echo $fruit . "\n" ;
}
?>
|
Output
apple
orange
banana
Split String by Delimiter using preg_split() Function and Regular Expression
The preg_split() function with a regular expression to split the string into an array, providing more flexibility for complex delimiter patterns.
PHP
<?php
$string = "apple,orange,banana" ;
$fruitsArray = preg_split( '/,/' , $string );
foreach ( $fruitsArray as $fruit ) {
echo $fruit . "\n" ;
}
?>
|
Output
apple
orange
banana
Split String by Delimiter using strtok() Function
The strtok() function to tokenize the string based on a specified delimiter (comma in this case) iteratively until no more tokens are found.
PHP
<?php
$string = "apple,orange,banana" ;
$token = strtok ( $string , ',' );
while ( $token !== false) {
echo $token . "\n" ;
$token = strtok ( ',' );
}
?>
|
Output
apple
orange
banana
Split String by Delimiter using sscanf() Function
Utilizes the sscanf() function with a format specifier to extract substrings separated by commas into separate variables, providing a structured way to split the string.
PHP
<?php
$string = "apple,orange,banana" ;
sscanf( $string , "%[^,],%[^,],%s" , $fruit1 , $fruit2 , $fruit3 );
echo $fruit1 . "\n" ;
echo $fruit2 . "\n" ;
echo $fruit3 . "\n" ;
?>
|
Output
apple
orange
banana
Split String by Delimiter using substr() and strpos() Functions
Manually splits the string by using substr() and strpos() to extract substrings before and after each comma, allowing for custom handling of each part of the split string.
PHP
<?php
$string = "apple,orange,banana" ;
$fruit1 = substr ( $string , 0, strpos ( $string , ',' ));
$restOfString = substr ( $string , strpos ( $string , ',' ) + 1);
$fruit2 = substr ( $restOfString , 0, strpos ( $restOfString , ',' ));
$fruit3 = substr ( $restOfString , strpos ( $restOfString , ',' ) + 1);
echo $fruit1 . "\n" ;
echo $fruit2 . "\n" ;
echo $fruit3 . "\n" ;
?>
|
Output
apple
orange
banana
Share your thoughts in the comments
Please Login to comment...