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
How to replace String in PHP ?
Replacing a string in PHP involves substituting parts of a string with another string. Common methods include str_replace() for simple replacements, preg_replace() for pattern-based replacements, substr_replace() for positional replacements, and str_ireplace() for case-insensitive replacements. Each
2 min read
How to Split a Delimited String to Access Individual Items in SQLite?
In SQLite, managing delimited strings can be a common requirement, especially when dealing with data that needs to be stored or manipulated in a database. Delimited strings are essentially strings where items are separated by a specific delimiter character, such as commas, pipes, or tabs. Splitting
4 min read
How to Split Explode Pandas DataFrame String Entry to Separate Rows
When working with Pandas, you may encounter columns with multiple values separated by a delimiter. To split these strings into separate rows, you can use the split() and explode() functions.str.split() splits the string into a list of substrings based on a delimiter (e.g., space, comma).explode() tr
2 min read
How to get a substring between two strings in PHP?
To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.Examples: Input:$string="hey, How are you?"If we need to extract the substring between "How" and "you" then the output should be are Output:"Are"Input:Hey, Welcome to Geeks
4 min read
How to insert a line break in PHP string ?
In this article, we will discuss how to insert a line break in a PHP string. We will get it by using the nl2br() function. This function is used to give a new line break wherever '\n' is placed.Syntax:nl2br("string \n");where the string is the input string.Example 1: PHP Program to insert a line bre
2 min read
How to Split a Delimited String to Access Individual Items in SQL?
In SQL, dealing with delimited strings is a common task, especially when handling data that are not structured in a traditional tabular format. Whether it's parsing a list of values separated by commas or any other delimiter, splitting these strings into individual items is crucial for various data
6 min read
PHP str_pad to print string patterns
str_pad: Pad a string to a certain length with another string. Syntax:- str_pad (input, pad_length, pad_string_value, pad_type) It returns the padded string. Parameters Description input:-The input string. pad_length:-If the value of pad_length is negative, less than, or equal to the length of the i
1 min read
How to read each character of a string in PHP ?
A string is a sequence of characters. It may contain integers or even special symbols. Every character in a string is stored at a unique position represented by a unique index value. Here are some approaches to read each character of a string in PHPTable of ContentUsing str_split() method - The str_
4 min read
How to remove Punctuation from String in PHP ?
Punctuation removal is often required in text processing and data cleaning tasks to prepare the text for further analysis or display. Below are the methods to remove punctuation from a string in PHP: Table of Content Using preg_replace with a Regular ExpressionUsing str_replace functionUsing preg_re
2 min read
How to Split a Delimited String to Access Individual Items in MySQL?
In MySQL, it's common to encounter scenarios where we need to split a delimited string into individual items to process or manipulate them separately. This can be achieved using the various techniques and functions provided by MySQL. This article will explore splitting a delimited string and accessi
3 min read