Home >Backend Development >PHP Tutorial >How Can I Efficiently Split a String into Lines Using PHP?
Splitting Strings with New Line Characters
For efficient string manipulation in programming, splitting a string based on specific characters is a common task. When dealing with multi-line text, it becomes necessary to divide the string into an array of lines.
To achieve this, we can utilize the preg_split() function, which takes two parameters: a regular expression and the string to be split. The regular expression defines the pattern to match against, and for new line characters, we specify the following pattern:
/\r\n|\n|\r/
This expression searches for line breaks (either a carriage return r, a newline n, or both rn) and uses it to split the string.
Here's an example:
$string = "My text1\nMy text2\nMy text3"; $array = preg_split("/\r\n|\n|\r/", $string); print_r($array);
Output:
Array ( [0] => My text1 [1] => My text2 [2] => My text3 )
As you can see, the string has been successfully split into an array of lines, with each line occupying an index in the array.
The above is the detailed content of How Can I Efficiently Split a String into Lines Using PHP?. For more information, please follow other related articles on the PHP Chinese website!