How to convert string to array using php
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 . "<br>"; }
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 . "<br>"; }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
