php split string to array
PHP: Split string into array, like explode with no delimiter
I have a string such as:
and need to split EACH character into an array.
I for the hell of it tried:
How would I come across this? I can’t see any method off hand, especially just a function
9 Answers 9
str_split takes an optional 2nd param, the chunk length (default 1), so you can do things like:
You can also get at parts of your string by treating it as an array:
What are you trying to accomplish? You can access characters in a string just like an array:
str_split can do the trick. Note that strings in PHP can be accessed just like a chars array, in most cases, you won’t need to split your string into a «new» array.
Here is an example that works with multibyte ( UTF-8 ) strings.
The above example will output:
If you want to split the string, it’s best to use:
When you have delimiter, which separates the string, you can try,
Where you can pass the delimiter in the first variable inside the explode such as:
will actuall work pretty fine, BUT if you want to preserve the special characters in that string, and you want to do some manipulation with them, THAN I would use
because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters
How can I put strings in an array, split by new line?
I have a string with line breaks in my database. I want to convert that string into an array, and for every new line, jump one index place in the array.
The result I want is this:
19 Answers 19
I’ve always used this with great success:
(updated with the final \r, thanks @LobsterMan)
You can use the explode function, using » \n » as separator:
For instance, if you have this piece of code:
You’d get this output:
Note that you have to use a double-quoted string, so \n is actually interpreted as a line-break.
(See that manual page for more details.)
A line break is defined differently on different platforms, \r\n, \r or \n.
Using RegExp to split the string you can match all three with \R
So for your problem:
That would match line breaks on Windows, Mac and Linux!
PHP already knows the current system’s newline character(s). Just use the EOL constant.
What’s happening is:
Since line breaks can come in different forms, I str_replace \r\n, \n\r, and \r with \n instead (and original \n are preserved).
Then explode on \n and you have all the lines in an array.
I did a benchmark on the src of this page and split the lines 1000 times in a for loop and:
preg_replace took an avg of 11 seconds
str_replace & explode took an avg of about 1 second
More detail and bencmark info on my forum
David: Great direction, but you missed \r. this worked for me:
PHP_EOL is a constant holding the line break character(s) used by the server platform.
The » (instead of ‘) is quite important as otherwise, the line break wouln’t get interpreted.
StackOverflow will not allow me to comment on hesselbom’s answer (not enough reputation), so I’m adding my own.
This worked best for me because it also eliminates leading (second \s*) and trailing (first \s*) whitespace automatically and also skips blank lines (the PREG_SPLIT_NO_EMPTY flag).
If you want to keep leading whitespace, simply get rid of the second \s* and make it an rtrim() instead.
If you need to keep empty lines, get rid of the NULL (it is only a placeholder) and PREG_SPLIT_NO_EMPTY flag, like so.
Or keeping both leading whitespace and empty lines.
I don’t see any reason why you’d ever want to keep trailing whitespace, so I suggest leaving the first \s* in there. But, if all you want is to split by new line (as the title suggests), it is THIS simple (as mentioned by Jan Goyvaerts).
As other answers have specified, be sure to use explode rather than split because as of PHP 5.3.0 split is deprecated. i.e. the following is NOT the way you want to do it:
LF = «\n» = chr(10), CR = «\r» = chr(13)
There is quite a mix of direct and indirect answers on this page and some good advice in comments, but there isn’t an answer that represents what I would write in my own project.
The OP makes no mention of trimming horizontal whitespace characters from the lines, so there is no expectation of removing \s or \h while exploding on variable (system agnostic) new lines.
While PHP_EOL is sensible advice, it lacks the flexibility appropriately explode the string when the newline sequence is coming from another operating system.
Using a non-regex explode will tend to be less direct because it will require string preparations. Furthermore, there may be mopping up after the the explosions if there are unwanted blank lines to remove.
str_split
str_split — Преобразует строку в массив
Описание
Преобразует строку в массив.
Список параметров
Максимальная длина фрагмента.
Возвращаемые значения
Примеры
Пример #1 Пример использования str_split()
Результат выполнения данного примера:
Примечания
Функция str_split() производит разбивку по байтам, а не по символам, в случае использования строк в многобайтных кодировках.
Смотрите также
User Contributed Notes 40 notes
A proper unicode string split;
print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));
A new version of «str_split_unicode» prev.
heres my version for php4 and below
The manual don’t says what is returned when you parse a different type of variable.
This is the example:
= «Long» ; // More than 1 char
$str2 = «x» ; // Only 1 char
$str3 = «» ; // Empty String
$str4 = 34 ; // Integer
$str5 = 3.4 ; // Float
$str6 = true ; // Bool
$str7 = null ; // Null
I noticed in the post below me that his function would return an array with an empty key at the end.
So here is just a little fix for it.
I needed a function that could split a string from the end with any left over chunk being at the beginning of the array (the beginning of the string).
The documentation fails to mention what happens when the string length does not divide evenly with the chunk size. Not sure if the same behavior for all versions of PHP so I offer the following code to determine this for your installation. On mine [version 5.2.17], the last chunk is an array the length of the remaining chars.
The very handy str_split() was introduced in PHP 5, but a lot of us are still forced to use PHP 4 at our host servers. And I am sure a lot of beginners have looked or are looking for a function to accomplish what str_split() does.
Taking advantge of the fact that strings are ‘arrays’ I wrote this tiny but useful e-mail cloaker in PHP, which guarantees functionality even if JavaScript is disabled in the client’s browser. Watch how I make up for the lack of str_split() in PHP 4.3.10.
// The result is an email address in HTML entities which, I hope most email address harvesters can’t read.
>
print cloakEmail ( ‘someone@nokikon.com’ );
?>
###### THE CODE ABOVE WITHOUT COMMENTS ######
It’s mentioned in the Return Values section above («If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element»), but note that an input of empty string will return array(1) < [0]=>string(0) «» >. Interestingly an input of NULL will also return array(1) < [0]=>string(0) «» >.
revised function from tatsudoshi
The previous suggestion is almost correct (and will only working for strlen=1. The working PHP4 function is:
Even shorter version:
//place each character (or group of) of the
string into and array
the fastast way (that fits my needs) to replace str_split() in php 4 i found is this:
implode
(PHP 4, PHP 5, PHP 7, PHP 8)
implode — Объединяет элементы массива в строку
Описание
Альтернативная сигнатура (не поддерживается с именованными аргументами):
Устаревшая сигнатура (устарела с PHP 7.4.0, удалена в PHP 8.0.0):
Список параметров
По умолчанию равен пустой строке.
Массив объединяемых строк.
Возвращаемые значения
Возвращает строку, содержащую строковое представление всех элементов массива в указанном порядке, с разделителем между каждым элементом.
Список изменений
Версия | Описание |
---|---|
8.0.0 | Передача separator после array больше не поддерживается. |
7.4.0 | Передача separator после array (т.е. использование недокументированного порядка параметров) устарела. |
Примеры
Пример #1 Пример использования implode()
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
User Contributed Notes 14 notes
it should be noted that an array with one or no elements works fine. for example:
It’s not obvious from the samples, if/how associative arrays are handled. The «implode» function acts on the array «values», disregarding any keys:
declare( strict_types = 1 );
Can also be used for building tags or complex lists, like the following:
?>
This is just an example, you can create a lot more just finding the right glue! 😉
It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.
$array = [
new Foo ( ‘foo’ ),
new Foo ( ‘bar’ ),
new Foo ( ‘qux’ )
];
TRUE became «1», FALSE became nothing.
Also quite handy in INSERT statements:
// build query.
$sql = «INSERT INTO table» ;
Even handier if you use the following:
This threw me for a little while.
If you want to implode an array as key-value pairs, this method comes in handy.
The third parameter is the symbol to be used between key and value.
// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo
null values are imploded too. You can use array_filter() to sort out null values.
Sometimes it’s necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.
If you want to use a key inside array:
Example:
$arr=array(
array(«id» => 1,»name» => «Test1»),
array(«id» => 2,»name» => «Test2»),
);
echo implode_key(«,»,$arr, «name»);
OUTPUT: Test1, Test2
It is possible for an array to have numeric values, as well as string values. Implode will convert all numeric array elements to strings.
PHP Explode: How to Split String into Array Elements in PHP
The explode() function in PHP allows us to break the string into smaller text, with each break occurring at the same symbol.
To convert PHP String to Array, use the explode() function.
PHP explode() function breaks the string into an array, but the implode function returns a string from the elements of an array.
PHP explode()
PHP explode() is a built-in function used to split the string by the specified string into array elements. The explode() function takes three arguments and returns an array containing elements of the string. The explode() function breaks the string into an array. The explode() function is binary-safe.
Syntax
Arguments
The separator parameter is required, and it specifies where we break the string.
The string parameter is required. It is the string to split.
The limit parameter is optional, and it specifies the number of array elements to return.
Implementation of explode() function
See the following example.
See the below output.
Passing limit parameter
See the following code where we pass the third parameter limit and see the output.
Use the negative limit and see the result.
See the below output.
Passing Multiple delimiters
You can pass the multiple delimiters to the explode() function.
See the following code.
How to split empty string in PHP
To split the empty string in PHP, use the explode() function.
See the following example.
If you split the empty string, you get back the one-element array with 0 as the key and the empty string for the value.
If we want to solve this then, use the array_filter() without callback. Quoting manual page, “If the callback function is not supplied, the array_filter() function will remove all the entries of input that are equal to FALSE.”
Trim whitespaces using explode() method
We can use the explode() function to trim the white space from the string.
With the help of the array_map() function and explode() function, we can trim the white spaces and split the string into an array. See the following code.
Explode does not parse the string by delimiters, in the sense that we expect to find tokens between the starting and ending delimiter, but instead splits the string into pieces by using the string as the boundary of each part.
Once that boundary is discovered, the string is split. Whether or not that limit is proceeded or superseded by any data is irrelevant since the parts are determined when a limit is discovered.
It should be said that when an empty delimiter is passed to explode, the function not only will return false but will also emit a warning. See the following code.
PHP explode vs. split
The main difference between the split() and explode() function is the way it uses to splitting a large string. Both the functions are used to split a string. However, the split() function is used to split a string using a regular expression, while the explode() function is used to split a string using another string.
One more point, the split() function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged; instead, use the explode() function.
The preg_split() is faster and uses PCRE regular expressions for regex splits.
Conclusion
So, if you want to break the string and create the array from it, then use the explode() function.
That is it for splitting a string in the PHP tutorial.