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" ; // 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" ; } ?> |
Output
apple orange banana
How to Split String by Delimiter/Separator in PHP?
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:
Table of Content
- Split String by Delimiter using explode() Function
- Split String by Delimiter using preg_split() Function and Regular Expression
- Split String by Delimiter using strtok() Function
- Split String by Delimiter using sscanf() Function
- Split String by Delimiter using substr() and strpos() Functions