Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to put string in array, split by new line in PHP...

How to put string in array, split by new line in PHP ?

Given a string concatenated with several new line character. The task is to split that string and store them into array such that strings are splitted by the newline.
Example: 
 

 Input : string is 'Ankit \n Ram \n Shyam'
 Output : Array
(
    [0] => Ankit
    [1] => Ram
    [2] => Shyam
)

Using explode() Function: The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string. This function accepts separator and string to be separated and optional argument length of string to be separated.
Example: 
 

php




<?php
 
// PHP program to separate string
// using explode function
 
// String which to be converted
$str = "Ankit Mishra\nRam Singh\nShyam Pandey";
 
// Function to convert string to array
$arr = explode("\n", $str);
 
// Print the information of array
print_r($arr);
?>


Output: 

Array
(
    [0] => Ankit Mishra
    [1] => Ram Singh
    [2] => Shyam Pandey
)

 

Using preg_split() Function: The function splits the string into smaller strings or sub-strings of length which is specified by the user. If the limit is specified then small string or sub-strings up to limit return through an array. The preg_split() function is similar to explode() function but the difference is used to the regular expression to specify the delimiter but explode is not used it. This function takes first argument as regular expression which is used for splitting second argument is as string which is to be splitted.
Example: 
 

php




<?php
 
// A php program to separate string
// using preg_split() function
 
// String which to be converted
$str = "Ankit Mishra\nRam Singh\nShyam Pandey";
 
// This function converts the string
$arr= preg_split ('/\n/', $str);
 
// print the information of array
print_r($arr);
?>


Output: 

Array
(
    [0] => Ankit Mishra
    [1] => Ram Singh
    [2] => Shyam Pandey
)

 

RELATED ARTICLES

Most Popular

Recent Comments