php разбить строку на массив по количеству символов
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:
Как разделить строку на части по количеству символов с переносом по словам?
Приветствую, коллеги!
Наведите на мысль, как разделить строку на части по количеству (не более) символов так чтоб не «резало» слова для записи в массив?
Пример: «Один Два Три Четыре Пять»
Делить, например, по 10
В результате:
Один Два(а не «Один Два Т»)
Три Четыре
Пять
Пробовал искать «последний» пробел, но не вариант т.к. за ним могут остаться символы..
Коллеги, спасибо всем, кто не пожалел своего времени на заданный вопрос!
Не зря говорят «Утро вечера мудренее..», сегодня с утра осенило ))
Решение оказалось банально простым, нужно в конце исходной строки добавить пробел чтоб потом спокойно искать его последнее вхождение.
В итоге мой конечный код выглядит так:
Ilyas Sarsenbaev предложил немного альтернативный вариант, его также попробовал адаптировав под свои реалии:
По затраченной памяти и скорости обработки оба скрипта примерно одинаковы, так что кому надо, можете использовать любой.
Еще раз спасибо всем участвовавшим в обсуждении.
Можно просто разделить строку по пробелу через функцию explode(), которая вернет массив и конкатенировать элементы массива добавив новую строку для каждого элемента.
Результат:
Один
Два
Три
Четыре
Пять
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.
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;
chunk_split
(PHP 4, PHP 5, PHP 7, PHP 8)
chunk_split — Разбивает строку на фрагменты
Описание
Функция используется для разбиения строки на фрагменты, например, для приведения результата функции base64_encode() в соответствие с требованиями RFC 2045. Она вставляет строку separator после каждых length символов.
Список параметров
Последовательность символов, используемая в качестве конца строки.
Возвращаемые значения
Возвращает преобразованную строку.
Примеры
Пример #1 Пример использования chunk_split()
Смотрите также
User Contributed Notes 20 notes
An alternative for unicode strings;
As an alternative for qeremy [atta] gmail [dotta] com
There is much shorter way for binarysafe chunking of multibyte string:
Not quite completely obvious, but.
you can un_chunk_split() by:
the best way to solve the problem with the last string added by chunk_split() is:
I’m not sure what versions this also occurs in but the output of chunk_split() in PHP 5.0.4 does not match the output in other versions of PHP.
In all versions of PHP I have used, apart from 5.0.4 chunk_split() adds the separator (\r\n) to the end of the string. But in PHP 5.0.4 this does not happen. This had a fairly serious impact on a library I maintain so it may also affect others who are not aware of this.
«version» of chunk_split for cyrillic characters in UTF-8
this is example for russian language
another way to group thousands in a number, which is much simpler, is built into PHP 🙂
Important note is the maximum line length and the recommended one. The standard says:
«Lines in a message MUST be a maximum of 998 characters excluding the CRLF, but it is RECOMMENDED that lines be limited to 78 characters excluding the CRLF. «
See PHP manual for chunk_split() Which is set to 76 characters long chunk and «\r\n» at the end of line by default.
If you are using UTF-8 charset you will face a problem with Arabic language
to solve this problem i used this function
Here’s a version of Chunk Split I wrote that will not split html entities. Useful if you need to inject something in html (in my case, tags to allow for long text wrapping).
>> chunk_split will also add the break _after_ the last occurence.
this should be not the problem
substr(chunk_split(‘FF99FF’, 2, ‘:’),0,8);
will return FF:99:FF
When using ssmtp for simple command line mailing:
I’ve found this quite useful for simulating various kinds of shuffles with cards. It is humorous but can imitate multiple deck cuts and other (imperfectly) random events.
This function is very simple and many other functions make this on PHP 5 and even some ones in 4 the good think about this one is that work on php 3.0.6 and 4
echo split_hjms_chars(«This is your text»,6,». «);
It is useful to cut long text on preview lists and if the server it’s old.
Hope it helps some one. Hans Svane
I think this is better, since you can still use the ampersand in your text:
Well I have been having issues with a shoutbox I am coding it would keep expanding the
This is a much simpler solution.
chunk_split() is not multibyte safe. If you ever run into needing the function that is multibyte safe, here you go: