How to Split String by Delimiter/Separator in PHP?
Last Updated :
09 Sep, 2024
Splitting a string by a delimiter in PHP is a common task that involves breaking a string into smaller components based on a specific character or pattern. This technique is essential for processing and manipulating strings in various applications, such as parsing CSV data or handling user inputs.
Examples:
Input: apple,orange,banana
Output:
apple
orange
banana
There are seven approaches to split the string, these are:
Using explode() Function
The explode() function in PHP splits a string into an array based on a specified delimiter. It's ideal for simple, single-character delimiters, and allows you to quickly separate string components. The function returns an array of substrings split by the delimiter.
Example : In this example we plits a string into an array by commas and outputs each element of the array, one per line, using a loop.
PHP
<?php
$string = "apple,orange,banana";
// Split the string into an array
// using the comma as a delimiter
$fruitsArray = explode(',', $string);
// Output each element of the
// resulting array
foreach ($fruitsArray as $fruit) {
echo $fruit . "\n";
}
?>
Outputapple
orange
banana
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.
Example: In this example we splits a string into an array using a regular expression to match commas, then outputs each element of the array in a loop.
PHP
<?php
$string = "apple,orange,banana";
// Split the string into an array using
// a regular expression to match commas
$fruitsArray = preg_split('/,/', $string);
// Output each element of the resulting array
foreach ($fruitsArray as $fruit) {
echo $fruit . "\n";
}
?>
Outputapple
orange
banana
Using strtok() Function
The strtok() function in PHP tokenizes a string by splitting it using specified delimiters. It returns each token one at a time, making it useful for iterative processing of string segments in a loop.
Example : in this example we tokenizes a string by commas using strtok, then outputs each token in a loop until no more tokens are found.
PHP
<?php
$string = "apple,orange,banana";
// Use strtok to tokenize the
// string based on commas
$token = strtok($string, ',');
// Output each token until there
// are no more
while ($token !== false) {
echo $token . "\n";
$token = strtok(',');
}
?>
Outputapple
orange
banana
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.
Example: In this example we are using sscanf to split a comma-separated string into variables, then outputs each fruit on a new line.
PHP
<?php
$string = "apple,orange,banana";
// Use sscanf to scan for non-comma
// characters and split the string
sscanf($string, "%[^,],%[^,],%s", $fruit1, $fruit2, $fruit3);
// Output each fruit
echo $fruit1 . "\n";
echo $fruit2 . "\n";
echo $fruit3 . "\n";
?>
Outputapple
orange
banana
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.
Example : In this example we splits a comma-separated string using substr and strpos, assigns each part to a variable, and then outputs each fruit on a new line.
PHP
<?php
$string = "apple,orange,banana";
// Split the string using substr and strpos
$fruit1 = substr($string, 0, strpos($string, ','));
$restOfString = substr($string, strpos($string, ',') + 1);
$fruit2 = substr($restOfString, 0, strpos($restOfString, ','));
$fruit3 = substr($restOfString, strpos($restOfString, ',') + 1);
// Output each fruit
echo $fruit1 . "\n";
echo $fruit2 . "\n";
echo $fruit3 . "\n";
?>
Outputapple
orange
banana
Using str_getcsv() Function
The str_getcsv() function is another way to split a string by a delimiter. This function is typically used to parse CSV data but can also be used for splitting strings based on a specified delimiter.
Example: This method is particularly useful when working with data that follows a CSV format or when needing a robust solution for splitting strings by delimiters.
PHP
<?php
// Sample input
$inputString = "apple,orange,banana";
// Using str_getcsv() to split the string by a comma
$delimiter = ",";
$result = str_getcsv($inputString, $delimiter);
foreach ($result as $item) {
echo $item . "\n";
}
?>
Outputapple
orange
banana
Similar Reads
PHP Program to Split & Join a String
Given a String, the task is to split and join strings in PHP. It is a common operations that allow you to manipulate and manage text data effectively. Below are the approaches to split and join a string in PHP: Table of Content Using explode() and implode() FunctionUsing str_split() and Custom Join
3 min read
How to put string in array, split by new line in PHP ?
Given a string concatenated with several new line character. The task is to split that string and store them into array such that strings are splitted by the newline.Example: Input : string is 'Ankit \n Ram \n Shyam' Output : Array ( [0] => Ankit [1] => Ram [2] => Shyam ) Using explode() Fu
2 min read
How to Extract Substring from a String in PHP?
Given a String, the task is to extract a substring from a string in PHP. Extracting substrings from a string is a common task in PHP, whether you need to extract a portion of text based on a specific position or find a substring based on a pattern. In this article, we will explore various approaches
3 min read
How to prepend a string in PHP?
We have given two strings and the task is to prepend a string str1 with another string str2 in PHP. There is no specific function to prepend a string in PHP. To do this task, we have the following operators in PHP: Below are the methods to prepend a string in PHP Table of Content Using Concatenation
2 min read
Split a comma delimited string into an array in PHP
Given a long string separated with a comma delimiter. The task is to split the given string with a comma delimiter and store the result in an array. Examples: Input: geeks,for,geeksOutput: Array ( [0] => geeks [1] => for [2] => geeks )Input: practice, codeOutput: Array ( [0] => practice
3 min read
How to remove extension from string in PHP?
There are three ways of removing an extension from string. They are as follows Using an inbuilt function pathinfo Using an inbuilt function basename Using an string functions substr and strrpos Using pathinfo() Function: The pathinfo() function returns an array containing the directory name, basenam
2 min read
How to Get All Substrings of a Given String in PHP ?
Extracting all possible substrings from a given string is a common task in text processing, pattern recognition, and various other applications in PHP programming. This operation involves generating every possible combination of characters present in the string, including both contiguous and non-con
3 min read
How to get parameters from a URL string in PHP?
The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: The page URL and the parameters are separated by the ? character. parse_url() FunctionThe parse_url() function is used to return the components of a URL by parsing it. It parses a URL and retu
2 min read
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|hardOutput: String 1: Sam|is|workingString 2: hardThere are four approaches to split the string,
5 min read
How to Replace Part of a string with Another String in PHP?
Given a String, the task is to replace the part of a string with another string in PHP. There are several methods to replace part of a string with another string. This operation is useful when you need to modify a string, such as replacing certain characters or substrings. Table of Content Using str
2 min read