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" ; // 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" ; ?> |
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
Contact Us