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
Release: 2024-12-08 00:01:13
Original
925 people have browsed it

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

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

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

For example, consider the input string:

My text1
My text2
My text3
Copy after login

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template