Home > Article > Backend Development > How to explode a string in php
How to explode a string in php?
In PHP, you can use the built-in function explode() to explode a string.
Recommended: "PHP Tutorial"
Definition and usage
explode() function breaks up a string into an array.
Note: The "separator" parameter cannot be an empty string.
Note: This function is binary safe.
Syntax
explode(separator,string,limit)
Parameters
separator required. Specifies where to split the string.
string Required. The string to split.
limit
Optional. Specifies the number of array elements to be returned.
Possible values:
Greater than 0 - Returns an array containing at most limit elements
Less than 0 - Returns an array containing all but the last -limit elements Array
0 - Returns an array containing one element
Return value: Returns an array of strings
Example 1
Break the string into an array :
<?php $str = "Hello world. I love Shanghai!"; print_r (explode(" ",$str)); ?>
Output:
Array ( [0] => Hello [1] => world. [2] => I [3] => love [4] => Shanghai! )
Use the limit parameter to return some array elements:
<?php $str = 'one,two,three,four'; // 零 limit print_r(explode(',',$str,0)); // 正的 limit print_r(explode(',',$str,2)); // 负的 limit print_r(explode(',',$str,-1)); ?>
Output:
Array ( [0] => one,two,three,four ) Array ( [0] => one [1] => two,three,four ) Array ( [0] => one [1] => two [2] => three )
The above is the detailed content of How to explode a string in php. For more information, please follow other related articles on the PHP Chinese website!