Home  >  Article  >  Backend Development  >  How to convert string to array using php

How to convert string to array using php

PHPz
PHPzOriginal
2023-04-19 09:18:41459browse

When developing PHP code, we sometimes need to split a string into multiple substrings according to newlines and store these substrings in an array. This article will introduce how to use PHP's built-in functions to quickly convert strings into arrays.

Use the explode() function to convert a string into an array

A quick and easy way is to use the built-in function explode(), which splits a string into multiple sub-arrays according to the specified delimiter. string and store these substrings into an array. For example, the following code splits a string into multiple substrings according to the "\n" newline character and prints each string:

// 定义需要转换的字符串
$str = "Hello\nWorld\nPHP\n";

// 按照换行符分割字符串,存储到数组中
$arr = explode("\n", $str);

// 遍历数组,并打印每个字符串
foreach ($arr as $str) {
    echo $str . "
"; }

The output result is:

Hello
World
PHP

Use preg_split( ) function to convert string to array

Another method is to use the regular expression function preg_split() to convert string to array. For example, the following code splits a string into multiple substrings according to newlines and prints each string:

// 定义需要转换的字符串
$str = "Hello\nWorld\nPHP\n";

// 按照换行符分割字符串,存储到数组中
$arr = preg_split('/\n/', $str, -1, PREG_SPLIT_NO_EMPTY);

// 遍历数组,并打印每个字符串
foreach ($arr as $str) {
    echo $str . "
"; }

The output result is:

Hello
World
PHP

Among them, the third parameter - 1 means not to limit the number of results returned, and the fourth parameter PREG_SPLIT_NO_EMPTY means to remove empty strings in the split results.

Summary

In PHP development, we often need to convert a string into an array according to newline characters. In order to quickly implement this process, you can use the built-in functions explode() and preg_split(). The former is simple to use, but its performance is slightly lower than the latter. No matter which method is used, the process of converting a string into an array can be quickly and conveniently implemented.

The above is the detailed content of How to convert string to array using 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