how to turn texts to be array by line with PHP
aaaaaaaaaaaa
bbbbbbbbbbbbbb
ccccccccccccc开发者_如何学Ccccccc
dddddddddddddddddd
I want turn to be a array base on line like that
array(
0=>'aaaaaaaaaaaa',
1=>'bbbbbbbbbbbbbb',
2=>'ccccccccccccccccccc',
3=>'dddddddddddddddddd'
)
How to do it with php?
$string = "aaaaaaaaaaaa
bbbbbbbbbbbbbb
ccccccccccccccccccc
dddddddddddddddddd";
$array = explode("\n", $string);
$arr = explode("\n", $str); // $str contains your text
The following is pretty flexible about line endings (newline or carriage return), or can be modified to include any space.
$lines = preg_split('/[\r\n]/', $text);
However, if you know the line ending to be \n
(newline) I would recommend explode()
as it avoids the regex overhead.
$lines = explode("\n", $text);
Read more on preg_split()
and explode()
.
$myArray = explode($your_seperator_string, $string_to_be_parsed_to_array);
PHP's explode(string $delimiter , string $string [, int $limit ])
function splits a string
by delimiter
.
In PHP, new lines are represented by \n
. Therefore, you can use explode()
to create an array after each new line.
$string = "aaaaaaaaaaa
bbbbbbbbb
cccccccccccccccc
ddddddddddd"
$string = "aaaaaaaaaaa\nbbbbbbbbb\ncccccccccccccccc\nddddddddddd"
//Both $string variables are the same
//Make sure that \n is in double quotes, single quotes WILL NOT WORK!!!
$array = explode("\n", $string);
There you go! Feel free to use array_map()
and other similar functions with the \n
to achieve the desired results.
Look into the split() method. PHP:split Manual
$myArray = split("[\n|\r]", $string);
Depending on the system that created the original string, you may or may not need the \r.
DEMO
<?php
$sample = "aaaaaaaaaaaa
bbbbbbbbbbbbbb
ccccccccccccccccccc
dddddddddddddddddd";
$ary = array_map("trim",explode("\n", $sample));
var_dump($ary);
OUTPUT:
array(4) {
[0]=>
string(12) "aaaaaaaaaaaa"
[1]=>
string(14) "bbbbbbbbbbbbbb"
[2]=>
string(19) "ccccccccccccccccccc"
[3]=>
string(18) "dddddddddddddddddd"
}
I use trim in case they are either \r\n or \n separated. Can also use regex, but figure I'd offer one more solution and the array_map
is optional.
$output_array = explode("\n<br />\n", $input_string);
精彩评论