Home >Backend Development >PHP Tutorial >How to Split a String by Newline Characters into an Array in PHP?

How to Split a String by Newline Characters into an Array in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 00:01:13915browse

How to Split a String by Newline Characters into an Array in PHP?

Splitting Strings by New Line Characters

In many programming scenarios, you may encounter strings that contain line breaks or new line characters. Converting such strings into an array can be crucial for further processing or analysis. This article addresses a common issue: how to split a string by new line characters and store the resulting segments in an array.

To achieve this, one of the most effective methods involves using the preg_split() function. This function enables you to split a string into an array based on a specified regular expression pattern. For instance, to split a string by new line characters, you can use the following regular expression:

/\r\n|\n|\r/

This pattern matches any of the common new line characters, including "rn" (Windows style), "n" (Unix style), and "r" (Macintosh style).

To apply this pattern, you can use the following code:

$array = preg_split("/\r\n|\n|\r/", $string);

where $string represents the original string containing the new line characters.

For example, consider the input string:

My text1
My text2
My text3

Running the above code on this string would produce the desired output:

Array
(
    [0] => My text1
    [1] => My text2
    [2] => My text3
)

Using this method, you can easily convert strings containing line breaks into arrays, making them easier to manipulate and process in your code.

The above is the detailed content of How to Split a String by Newline Characters into an 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