Home  >  Article  >  Backend Development  >  How to split string and convert into array in php

How to split string and convert into array in php

PHPz
PHPzOriginal
2023-04-18 10:18:061262browse

In PHP, it is often necessary to split strings into arrays to achieve more convenient processing of strings. This article introduces two methods of converting split strings into arrays.

Method 1: Use the explode function

The explode function is one of the commonly used string functions in PHP. It can split a string into an array according to the specified delimiter. The explode function takes two parameters: the first parameter is the delimiter used, and the second parameter is the string to be split. The following is a sample code that uses the explode function to split a string into an array:

$str = "apple,banana,orange";
$arr = explode(",", $str);
print_r($arr);

The output result is:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

Method 2: Use the preg_split function

In addition to using the explode function , you can also use the preg_split function to split the string into an array. The preg_split function can use regular expressions as separators, which gives users greater flexibility. The following is a sample code that uses the preg_split function to split a string into an array:

$str = "apple,banana,orange";
$arr = preg_split("/,/", $str);
print_r($arr);

The output result is the same as using the explode function:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

Of course, the above two methods have their own advantages and disadvantages. The explode function is a function specially used to split strings and is simple and clear to use; while the preg_split function can use more complex delimiters and is more flexible. Which method to use can be chosen based on actual needs.

Summary

This article introduces two methods of converting split strings into arrays. Whether you use the explode function or the preg_split function, you can easily split the string into an array to facilitate better processing of the string. At the same time, we also need to pay attention to the respective advantages, disadvantages and scope of application of these two methods in order to choose the most appropriate method.

The above is the detailed content of How to split string and convert into array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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