Home > Backend Development > PHP Problem > How to use php explode function?

How to use php explode function?

藏色散人
Release: 2023-02-22 22:44:01
Original
2921 people have browsed it

php explode function is used to break up strings into arrays. Its syntax is explode(separator, string, limit). The parameter separator is required and specifies where to split the string; string is required and refers to the string to be split.

How to use php explode function?

#How to use php explode function?

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)
Copy after login

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

PHP Version: 4

Update log:

In PHP 4.0.1, the limit parameter is added. In PHP 5.1.0, support for negative limits was added.

Example 1

Use the limit parameter to return some array elements:

<?php
$str = &#39;one,two,three,four&#39;;
// 零 limit
print_r(explode(&#39;,&#39;,$str,0));
// 正的 limit
print_r(explode(&#39;,&#39;,$str,2));
// 负的 limit
print_r(explode(&#39;,&#39;,$str,-1));
?>
Copy after login

Output:

Array ( [0] => one,two,three,four ) Array ( [0] => one [1] => two,three,four ) Array ( [0] => one [1] => two [2] => three )
Copy after login

Example 2

Break the string into an array:

<?php
$str = "Hello world. I love Shanghai!";
print_r (explode(" ",$str));
?>
Copy after login

Output:

Array ( [0] => Hello [1] => world. [2] => I [3] => love [4] => Shanghai! )
Copy after login

The above is the detailed content of How to use php explode function?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template