How to Split String in PHP: Syntax and Examples
In PHP, you can split a string into parts using the
explode() function, which breaks the string by a specified delimiter and returns an array of substrings. The syntax is explode(delimiter, string), where delimiter is the character or string to split by.Syntax
The explode() function splits a string into an array using a delimiter.
- delimiter: The character(s) where the string will be split.
- string: The original string to split.
- limit (optional): Maximum number of elements in the returned array.
php
array explode(string $delimiter, string $string, int $limit = PHP_INT_MAX);Example
This example splits a sentence into words using space as the delimiter and prints each word.
php
<?php $text = "Hello world from PHP"; $words = explode(" ", $text); foreach ($words as $word) { echo $word . "\n"; } ?>
Output
Hello
world
from
PHP
Common Pitfalls
Common mistakes include:
- Using the wrong delimiter that does not exist in the string, resulting in the whole string returned as one element.
- Forgetting that
explode()returns an array, so you must handle it accordingly. - Not using the optional
limitparameter when you want to control the number of splits.
php
<?php // Wrong delimiter example $text = "apple,banana,orange"; $fruits = explode(";", $text); // Wrong delimiter var_dump($fruits); // Outputs whole string as one element // Correct delimiter $fruits = explode(",", $text); var_dump($fruits); ?>
Output
array(1) {
[0]=>
string(19) "apple,banana,orange"
}
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(6) "banana"
[2]=>
string(6) "orange"
}
Quick Reference
Remember these tips when splitting strings in PHP:
- Use
explode()to split by a delimiter. - The delimiter can be any string, like space, comma, or dash.
- The result is always an array.
- Use the optional
limitto control how many pieces you get.
Key Takeaways
Use
explode() to split strings by a delimiter in PHP.The function returns an array of substrings split at each delimiter.
Choose the correct delimiter to get expected results.
Remember to handle the returned array properly.
Use the optional limit parameter to control the number of splits.