php split string by symbol
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:
split
split — Разбиение строки на массив по регулярному выражению
Эта функция объявлена УСТАРЕВШЕЙ в PHP 5.3.0, и УДАЛЕНА PHP 7.0.0.
Есть следующие альтернативы:
Описание
Разбивает строку string на массив по регулярному выражению.
Список параметров
Регулярное выражение, чувствительное к регистру.
Возвращаемые значения
Примеры
Пример #1 Пример использования split()
Получаем первые четыре поля строки из /etc/passwd :
Пример #2 Пример использования split()
Распознаем дату, отформатированную с использованием слешей, точек или дефисов:
Примечания
Смотрите также
User Contributed Notes 25 notes
In response to the getCSVValues() function posted by justin at cam dot org, my testing indicates that it has a problem with a CSV string like this:
To fix this, I changed the second substr_count to look for an odd number of quotes, as opposed to any quotes at all:
moritz’s quotesplit didn’t work for me. It seemed to split on a comma even though it was between a pair of quotes. However, this did work:
//$instring toggles so we know if we are in a quoted string or not
$delimlen = strlen($splitter);
$instring = 0;
strange things happen with split
If you want to use split to check on line feeds (\n), the following won’t work:
Took me a little while to figure out.
It’s evident but not mentioned in the documentation that using asterisks is more restricted than in a normal regular expression.
for exaple you cannot say:
because what if there’s no «;» separator?(which is covered by this regular expression)
so you have to use at least
I’ve try using split function.
I use charset UTF-8. When I use char � the split function ad an empty string between «2» and «12». Why?
UTF-8 charset codes some characters (like the «�» character) into two bytes. In fact the regular expresion «[�]» contains 4 bytes (4 non-unicode characters). To demonstrate the real situation I wrote following example:
In answer to gwyne at gmx dot net, dec 1, 2002:
For split(), when using a backslash as the delimiter, you have to *double escape* the backslash.
A correction to a earlier note
If you want to use split to check on line feeds (\n), the following won’t work:
Took me a little while to figure to do
The following has worked for me to get a maximum of 2 array parts separated by the first new line (independant if saved under UNIX or WINDOWS):
$line = preg_split(‘/[\n\r]+/’,$input_several_lines_long,2);
Also empty lines are not considered here.
[Ed. note: Close. The pipe *is* an operator in PHP, but
the reason this fails is because it’s also an operator
in the regex syntax. The distinction here is important
since a PHP operator inside a string is just a character.]
The reason your code:
didn’t work is because the «|» symbol is an operator in PHP. If you want to use the pipe symbol as a delimiter you must excape it with a back slash, «\|». You code should look like this:
split() doesn’t like NUL characters within the string, it treats the first one it meets as the end of the string, so if you have data you want to split that can contain a NUL character you’ll need to convert it into something else first, eg:
Thank you Dave for your code below. Here is one change I made to avoid a redundant quote at the end of some lines (at least when I used excel:
// Is the last thing a quote?
if ($trim_quote) <
// Well then get rid of it
—$length;
// ADD TO FIX extra quote
—$length;
>
wchris’s quotesplit assumes that anything that is quoted must also be a complete delimiter-seperated entry by itself. This version does not. It also uses split’s argument order.
//$instring toggles so we know if we are in a quoted string or not
$delimlen = strlen($splitter);
$instring = 0;
Though this is obvious, the manual is a bit incorrect when claiming that the return will always be 1+number of time the split pattern occures. If the split pattern is the first part of the string, the return will still be 1. E.g.
$a = split(«zz,» «zzxsj.com»);
count($a);
The return of this can not in anyway be seperated from the return where the split pattern is not found.
I’d like to correct myself, I found that after testing my last solution it will create 5 lines no matter what. So I added this to make sure that it only displays 5 if there are five newlines. 🙂
Those of you trying to use split for CSV, it won’t always work as expected. Instead, try using a simple stack method:
>
else <
// It’s a closing quote
$quote_open = false ;
// Trim the last quote?
$trim_quote = true ;
>
?>
This *should* work for any valid CSV string, regardless of what it contains inside its quotes (using RFC 4180). It should also be faster than most of the others I’ve seen. It’s very simple in concept, and thoroughly commented.
If you need to do a split on a period make sure you escape the period out..
$ext_arr = split(«\.»,»something.jpg»);
. because
$ext_arr = split(«.»,»something.jpg»); won’t work properly.
Actually, this version is better than the last I submitted. The goal here is to be able to engage in *multiple* delimeter removal passes; for all but the last pass, set the third value to «1», and everything should go well.
//$instring toggles so we know if we are in a quoted string or not
$delimlen = strlen($splitter);
$instring = 0;
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.
PHP Split String
By Shree Ram Sharma
Introduction to PHP Split String
The split string is one of the basic operations for any programming language. There are various built-in functions in PHP to deal with split relation operations. When we come to know the word split, we will experience the breaking of a single string into the multiple strings. There are various ways we can split a string as per our business requirements. In other words, if you want to split a string to get the string character by character (1 character each), by space, by special character etc. We can also go with the size combination while dealing with the string split.
Syntax:
Web development, programming languages, Software testing & others
explode(Separator, String, Limit)
The limit is an optional parameter.
preg_split(RegularExpressionPattern, String, Limit, Flags)
RegularExpressionPattern- required parameter.
Working of PHP Split String
Before moving ahead with the string split, we must have a string first to perform the operation on that string. After string, we can come to the required delimiter upon which the string split operation needs to perform.
1. User of explode() Function
This function can be used to break a string into an array of string.
Let’s understand the same with a basic example:
2. The User of preg_split()
The above of the code will break the string either by – or by the white space.
3. The user of str_split
This can also do the same job, converting a string to an array of smaller strings.
$string = «Welcome to the India»; // a string
$outputArr = str_split(«Welcome to the India»);
Examples to Implement PHP Split String
Below are the Example of PHP Split String:
Example #1
Split a string where we find the white space.
Code:
Output:
Example #2
In this example, we will see how a string can be split into multiple strings using a regular expression.
Code:
Output:
Example #3
Let’s see another very simple example of string split using the str_split() function.
Code:
«;
echo «Array of string after string str_split:\n»;
$arrays = str_split($string);
print_r($arrays);
?>
Output:
Example #4
String split using str_split() function with a specified length.
Code:
Output:
Explanation: Looking at the output of the above program, we can say that some string of length 2 or 3 but we have mentioned the length as a 4. This is just because the string element with 2 carries 2 spaces and the string with 3 characters carry one space with it.
Example #5
Now, using the string split method lets try to get the first string from of that string.
Code:
Output:
Conclusion
We can simply say, in PHP there are various ways to handle the string split. Built-in PHP functions can be used as per the business requirements to process the split string. But code or developer should be aware of using these and the pros and cons of it. Most of the functions of the string split changed the string into an array then we can get the specified string from that array.
Recommended Article
This is a guide to the PHP Split String. Here we discuss the Introduction of PHP Split String and its Examples and Code Implementation. You can also go through our other suggested articles to learn more –
mb_split
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
mb_split — Разделение строк в многобайтных кодировках, используя регулярное выражение
Описание
Список параметров
Шаблон регулярного выражения.
Разбиваемая строка ( string ).
limit Если необязательный аргумент limit задан, функция разобьёт строку не более, чем на limit частей.
Возвращаемые значения
Результат разбиения в виде массива ( array ) или false в случае возникновения ошибки.
Примечания
Смотрите также
User Contributed Notes 8 notes
a (simpler) way to extract all characters from a UTF-8 string to array with a single call to a built-in function:
I figure most people will want a simple way to break-up a multibyte string into its individual characters. Here’s a function I’m using to do that. Change UTF-8 to your chosen encoding method.
In addition to Sezer Yalcin’s tip.
This function splits a multibyte string into an array of characters. Comparable to str_split().
To split an string like this: «日、に、本、ほん、語、ご» using the «、» delimiter i used:
The solution was to set this before:
mb_regex_encoding(‘UTF-8’);
mb_internal_encoding(«UTF-8»);
$v = mb_split(‘、’,»日、に、本、ほん、語、ご»);
and now it’s working:
this is my solution for it:
an other way to str_split multibyte string:
= ‘әӘөүҗңһ’ ;
We are talking about Multi Byte ( e.g. UTF-8) strings here, so preg_split will fail for the following string:
‘Weiße Rosen sind nicht grün!’
And because I didn’t find a regex to simulate a str_split I optimized the first solution from adjwilli a bit:
( ‘UTF-8’ );
mb_regex_encoding ( ‘UTF-8’ );
echo » ;
?>
Let me know [by personal email], if someone found a regex to simulate a str_split with mb_split.