str_split
Если указан необязательный параметр length , возвращаемый массив будет разбит на фрагменты, каждый из которых будет иметь длину length , за исключением последнего фрагмента, который может быть короче, если строка делится неравномерно. По умолчанию параметр length равен 1 , то есть размер каждого фрагмента будет один байт.
Ошибки
Если параметр length меньше 1 , будет выброшена ошибка ValueError .
Список изменений
| Версия | Описание |
|---|---|
| 8.0.0 | Теперь если параметр length меньше 1 , будет выброшена ошибка ValueError ; ранее, вместо этого выдавалась ошибка уровня E_WARNING , а функция возвращала false . |
Примеры
Пример #1 Пример использования str_split()
$str = «Hello Friend» ;
$arr1 = str_split ( $str );
$arr2 = str_split ( $str , 3 );
print_r ( $arr1 );
print_r ( $arr2 );
Результат выполнения данного примера:
Примечания
Замечание:
Функция str_split() производит разбивку по байтам, а не по символам, в случае использования строк в многобайтных кодировках. Используйте функцию mb_str_split() , чтобы разбить строку на кодовые точки.
Смотрите также
- mb_str_split() — Если задана многобайтовая строка возвращает массив символов
- chunk_split() — Разбивает строку на фрагменты
- preg_split() — Разбивает строку по регулярному выражению
- explode() — Разбивает строку с помощью разделителя
- count_chars() — Возвращает информацию о символах, входящих в строку
- str_word_count() — Возвращает информацию о словах, входящих в строку
User Contributed Notes 3 notes
The function str_split() is not ‘aware’ of words. Here is an adaptation of str_split() that is ‘word-aware’.
$array = str_split_word_aware (
‘In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep.’ ,
32
);
/**
* This function is similar to str_split() but this function keeps words intact; it never splits through a word.
*
* @return array<int, string>
*/
function str_split_word_aware ( string $string , int $maxLengthOfLine ): array
<
if ( $maxLengthOfLine <= 0 ) <
throw new RuntimeException ( sprintf ( ‘The function %s() must have a max length of line at least greater than one’ , __FUNCTION__ ));
>
$lines = [];
$words = explode ( ‘ ‘ , $string );
$currentLine = » ;
$lineAccumulator = » ;
foreach ( $words as $currentWord ) <
$currentWordWithSpace = sprintf ( ‘%s ‘ , $currentWord );
$lineAccumulator .= $currentWordWithSpace ;
if ( strlen ( $lineAccumulator ) < $maxLengthOfLine ) <
$currentLine = $lineAccumulator ;
continue;
>
// Overwrite the current line and accumulator with the current word
$currentLine = $currentWordWithSpace ;
$lineAccumulator = $currentWordWithSpace ;
>
if ( $currentLine !== » ) <
$lines [] = $currentLine ;
>
array( 5 ) <
[ 0 ]=> string ( 29 ) «In the beginning God created »
[ 1 ]=> string ( 30 ) «the heaven and the earth. And »
[ 2 ]=> string ( 28 ) «the earth was without form, »
[ 3 ]=> string ( 27 ) «and void; and darkness was »
[ 4 ]=> string ( 27 ) «upon the face of the deep. »
>
preg_split
Если указан, функция возвращает не более, чем limit подстрок. Оставшаяся часть строки будет возвращена в последней подстроке. Специальное значение limit , равное -1 или 0, подразумевает отсутствие ограничения.
flags может быть любой комбинацией следующих флагов (объединённых с помощью побитового оператора | ): PREG_SPLIT_NO_EMPTY Если указан этот флаг, функция preg_split() вернёт только непустые подстроки. PREG_SPLIT_DELIM_CAPTURE Если указан этот флаг, выражение, заключённое в круглые скобки в разделяющем шаблоне, также извлекается из заданной строки и возвращается функцией. PREG_SPLIT_OFFSET_CAPTURE
Если указан этот флаг, для каждой найденной подстроки будет указана её позиция в исходной строке. Необходимо помнить, что этот флаг меняет формат возвращаемого массива: каждый элемент будет содержать массив, содержащий в индексе с номером 0 найденную подстроку, а смещение этой подстроки в параметре subject — в индексе 1 .
Возвращаемые значения
Возвращает массив, состоящий из подстрок заданной строки subject , которая разбита по границам, соответствующим шаблону pattern или false в случае возникновения ошибки.
Ошибки
Если переданный шаблон регулярного выражения не компилируется в допустимое регулярное выражение, выдаётся ошибка уровня E_WARNING .
Примеры
Пример #1 preg_split() пример: Получение подстрок из заданного текста
Результат выполнения данного примера:
Пример #2 Разбиваем строку на составляющие символы
Результат выполнения данного примера:
Пример #3 Разбиваем строку с указанием смещения для каждой из найденных подстрок
Результат выполнения данного примера:
Примечания
Если вам не нужна мощь регулярных выражений, вы можете выбрать более быстрые (хоть и простые) альтернативы наподобие explode() или str_split() .
Если соответствий не нашлось, то возвращается массив с единственным элементом равным всей строке.
Смотрите также
- "Регулярные выражения PCRE"
- preg_quote() — Экранирует символы в регулярных выражениях
- implode() — Объединяет элементы массива в строку
- preg_match() — Выполняет проверку на соответствие регулярному выражению
- preg_match_all() — Выполняет глобальный поиск шаблона в строке
- preg_replace() — Выполняет поиск и замену по регулярному выражению
- preg_last_error() — Возвращает код ошибки выполнения последнего регулярного выражения PCRE
User Contributed Notes 18 notes
Sometimes PREG_SPLIT_DELIM_CAPTURE does strange results.
<?php
$content = ‘<strong>Lorem ipsum dolor</strong> sit <img src=»https://www.php.net/manual/ru/test.png» />amet <span style=»color:red»>consec<i>tet</i>uer</span>.’ ;
$chars = preg_split ( ‘/<[^>]*[^\/]>/i’ , $content , — 1 , PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
print_r ( $chars );
?>
Produces:
Array
(
[0] => Lorem ipsum dolor
[1] => sit <img src=»https://www.php.net/manual/ru/test.png» />amet
[2] => consec
[3] => tet
[4] => uer
)
So that the delimiter patterns are missing. If you wanna get these patters remember to use parentheses.
<?php
$chars = preg_split ( ‘/(<[^>]*[^\/]>)/i’ , $content , — 1 , PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
print_r ( $chars ); //parentheses added
?>
Produces:
Array
(
[0] => <strong>
[1] => Lorem ipsum dolor
[2] => </strong>
[3] => sit <img src=»https://www.php.net/manual/ru/test.png» />amet
[4] => <span style=»color:red»>
[5] => consec
[6] => <i>
[7] => tet
[8] => </i>
[9] => uer
[10] => </span>
[11] => .
)
Assuming you’re using UTF-8, this function can be used to separate Unicode text into individual codepoints without the need for the multibyte extension.
preg_split ( ‘//u’ , $text , — 1 , PREG_SPLIT_NO_EMPTY );
?>
The words «English», «Español», and «Русский» are all seven letters long. But strlen would report string lengths 7, 8 and 14, respectively. The preg_split above would return a seven-element array in all three cases.
It splits ‘한국어’ into the array [‘한’, ‘국’, ‘어’] instead of the 9-character array that str_split($text) would produce.
Extending m.timmermans’s solution, you can use the following code as a search expression parser:
<?php
$search_expression = «apple bear \»Tom Cruise\» or ‘Mickey Mouse’ another word» ;
$words = preg_split ( «/[\s,]*\\\»([^\\\»]+)\\\»[\s,]*|» . «[\s,]*'([^’]+)'[\s,]*|» . «[\s,]+/» , $search_expression , 0 , PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
print_r ( $words );
?>
The result will be:
Array
(
[0] => apple
[1] => bear
[2] => Tom Cruise
[3] => or
[4] => Mickey Mouse
[5] => another
[6] => word
)
1. Accepted delimiters: white spaces (space, tab, new line etc.) and commas.
2. You can use either simple (‘) or double («) quotes for expressions which contains more than one word.
This regular expression will split a long string of words into an array of sub-strings, of some maximum length, but only on word-boundries.
I use the reg-ex with preg_match_all(); but, I’m posting this example here (on the page for preg_split()) because that’s where I looked when I wanted to find a way to do this.
Hope it saves someone some time.
<?php
// example of a long string of words
$long_string = ‘Your IP Address will be logged with the submitted note and made public on the PHP manual user notes mailing list. The IP address is logged as part of the notes moderation process, and won\’t be shown within the PHP manual itself.’ ;
// «word-wrap» at, for example, 60 characters or less
$max_len = 60 ;
// this regular expression will split $long_string on any sub-string of
// 1-or-more non-word characters (spaces or punctuation)
if( preg_match_all ( «/. <1, < $max_len >>(?=\W+)/» , $long_string , $lines ) !== False ) <
// $lines now contains an array of sub-strings, each will be approx.
// $max_len characters — depending on where the last word ended and
// the number of ‘non-word’ characters found after the last word
for ( $i = 0 ; $i < count ( $lines [ 0 ]); $i ++) <
echo «[ $i ] < $lines [ 0 ][ $i ]>\n» ;
>
>
?>
Here is another way to split a CamelCase string, which is a simpler expression than the one using lookaheads and lookbehinds:
preg_split(‘/([[:upper:]][[:lower:]]+)/’, $last, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY)
It makes the entire CamelCased word the delimiter, then returns the delimiters (PREG_SPLIT_DELIM_CAPTURE) and omits the empty values between the delimiters (PREG_SPLIT_NO_EMPTY)
If you want to split by a char, but want to ignore that char in case it is escaped, use a lookbehind assertion.
In this example a string will be split by «:» but «\:» will be ignored:
<?php
$string = ‘a:b:c\:d’ ;
$array = preg_split ( ‘#(?<!\\\)\:#’ , $string );
print_r ( $array );
?>
Results into:
preg_split() behaves differently from perl’s split() if the string ends with a delimiter. This perl snippet will print 5:
my @a = split(/ /, «a b c d e «);
print scalar @a;
The corresponding php code prints 6:
<?php print count ( preg_split ( «/ /» , «a b c d e » )); ?>
This is not necessarily a bug (nowhere does the documentation say that preg_split() behaves the same as perl’s split()) but it might surprise perl programmers.
To clarify the «limit» parameter and the PREG_SPLIT_DELIM_CAPTURE option,
<?php
$preg_split ( ‘(/ /)’ , ‘1 2 3 4 5 6 7 8’ , 4 , PREG_SPLIT_DELIM_CAPTURE );
?>
returns:
(‘1’, ‘ ‘, ‘2’, ‘ ‘ , ‘3’, ‘ ‘, ‘4 5 6 7 8’)
So you actually get 7 array items not 4
You must be caution when using lookbehind to a variable match.
For example:
‘/(?<!\\\)\r?\n)/’
to match a new line when not \ is before it don’t go as spected as it match \r as the lookbehind (becouse isn’t a \) and is optional before \n.
You must use this for example:
‘/((?<!\\\|\r)\n)|((?<!\\\)\r\n)/’
That match a alone \n (not preceded by \r or \) or a \r\n not preceded by a \.
Beware that it is not safe to assume there are no empty values returned by PREG_SPLIT_NO_EMPTY, nor that you will see no delimiters if you use PREG_SPLIT_DELIM_CAPTURE, as there are some edge cases where these are not true.
<?php
# As expected, splitting a string by itself returns two empty strings:
var_export ( preg_split ( «/x/» , «x» ));
# But if we add PREG_SPLIT_NO_EMPTY, then instead of an empty array, we get the delimiter.
var_export ( preg_split ( «/x/» , «x» , PREG_SPLIT_NO_EMPTY ));
And if we try to split an empty string , then instead of an empty array, we get an empty string even with PREG_SPLIT_NO_EMPTY .
var_export ( preg_split ( «/x/» , «» , PREG_SPLIT_NO_EMPTY ));
This is a function to truncate a string of text while preserving the whitespace (for instance, getting an excerpt from an article while maintaining newlines). It will not jive well with HTML, of course.
<?php
/**
* Truncates a string of text by word count
* @param string $text The text to truncate
* @param int $max_words The maximum number of words
* @return string The truncated text
*/
function limit_words ( $text , $max_words ) <
$split = preg_split ( ‘/(\s+)/’ , $text , — 1 , PREG_SPLIT_DELIM_CAPTURE );
$truncated = » ;
for ( $i = 0 ; $i < min ( count ( $split ), $max_words * 2 ); $i += 2 ) <
$truncated .= $split [ $i ]. $split [ $i + 1 ];
>
return trim ( $truncated );
>
?>
To split a camel-cased string using preg_split() with lookaheads and lookbehinds:
<?php
function splitCamelCase ( $str ) <
return preg_split ( ‘/(?<=\\w)(?=[A-Z])/’ , $str );
>
?>
Как разбить строку на символы php
$arr1 = str_split ( $str );
$arr2 = str_split ( $str , 3 );
print_r ( $arr1 );
print_r ( $arr2 );
- mb_str_split() — Если задана многобайтовая строка возвращает массив символов
- chunk_split() — Разбивает строку на фрагменты
- preg_split() — Разбивает строку по регулярному выражению
- explode() — Разбивает строку с помощью разделителя
- count_chars() — Возвращает информацию о символах, входящих в строку
- str_word_count() — Возвращает информацию о словах, входящих в строку
User Contributed Notes 40 notes
A proper unicode string split;
<?php
function str_split_unicode ( $str , $l = 0 ) if ( $l > 0 ) $ret = array();
$len = mb_strlen ( $str , «UTF-8» );
for ( $i = 0 ; $i < $len ; $i += $l ) $ret [] = mb_substr ( $str , $i , $l , «UTF-8» );
>
return $ret ;
>
return preg_split ( «//u» , $str , — 1 , PREG_SPLIT_NO_EMPTY );
>
?>
print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));
A new version of «str_split_unicode» prev.
<?php
function str_split_unicode ( $str , $length = 1 ) $tmp = preg_split ( ‘
u’ , $str , — 1 , PREG_SPLIT_NO_EMPTY );
if ( $length > 1 ) $chunks = array_chunk ( $tmp , $length );
foreach ( $chunks as $i => $chunk ) $chunks [ $i ] = join ( » , (array) $chunk );
>
$tmp = $chunks ;
>
return $tmp ;
>
?>
Version of str_split by rlpvandenberg at hotmail dot com is god-damn inefficient and when $i+$j > strlen($text) [last part of string] throws a lot of notice errors. This should work better:
if(! function_exists(‘str_split’))
function str_split($text, $split = 1)
$array = array();
for ($i = 0; $i < strlen($text);)
$array[] = substr($text, $i, $split);
$i += $split;
>
For those it may concern:
We encountered trubble when trying to str_split a UTF-8 encoded string, containing such Swedish letters as å, å and ö.
It seems that this function splits according to byte-length and not character length. So if the letter «Å» takes 2 bytes, then str_split() will only return the first bite of the character «Å».
We ain’t 100% sure that this is the case but this was anyhow the result we got. So we used the multi-byte functions instead.
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.
//Create a string split function for pre PHP5 versions
function str_split ( $str , $nr )
//Return an array with 1 less item then the one we have
return array_slice ( split ( «-l-» , chunk_split ( $str , $nr , ‘-l-‘ )), 0 , — 1 );
i use this in PHP4
function str_split($str) return preg_split(‘//’,$str);
>
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 manual don’t says what is returned when you parse a different type of variable.
This is the example:
$str1 = «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
$spl1 = str_split ( $str1 );
$spl2 = str_split ( $str2 );
$spl3 = str_split ( $str3 );
$spl4 = str_split ( $str4 );
$spl5 = str_split ( $str5 );
$spl6 = str_split ( $str6 );
$spl7 = str_split ( $str7 );
echo count ( $spl1 ); // 4
echo count ( $spl2 ); // 1
echo count ( $spl3 ); // 1
echo count ( $spl4 ); // 2
echo count ( $spl5 ); // 3
echo count ( $spl6 ); // 1
echo count ( $spl7 ); // 1
print_r ( $spl1 );
print_r ( $spl2 );
print_r ( $spl3 );
print_r ( $spl4 );
print_r ( $spl5 );
print_r ( $spl6 );
print_r ( $spl7 );
revised function from tatsudoshi
Fixed some bugs, more php5 style compliant
<?php
if(! function_exists ( ‘str_split’ )) function str_split ( $string , $string_length = 1 ) if( strlen ( $string )> $string_length || ! $string_length ) do $c = strlen ( $string );
$parts [] = substr ( $string , 0 , $string_length );
$string = substr ( $string , $string_length );
> while( $string !== false );
> else $parts = array( $string );
>
return $parts ;
>
>
?>
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) . Interestingly an input of NULL will also return array(1) .
Compare this with, say, <?php preg_split ( ‘//’ , $inputString , — 1 , PREG_SPLIT_NO_EMPTY ); ?> which will return array(0) for an input of empty string or NULL. I find this to be a bit more intuitive.
Hope this helps.
The previous suggestion is almost correct (and will only working for strlen=1. The working PHP4 function is:
<code>
function str_split($text, $split = 1) //place each character of the string into and array
$array = array();
for ($i=0; $i < strlen($text); $i++) $key = «»;
for ($j = 0; $j < $split; $j++) $key .= $text[$i+$j];
>
$i = $i + $j — 1;
array_push($array, $key);
>
return $array;
>
</code>
here an equivalent function for unicode string :
<?php
function uni_strsplit ( $string , $split_length = 1 )
preg_match_all ( ‘`.`u’ , $string , $arr );
$arr = array_chunk ( $arr [ 0 ], $split_length );
$arr = array_map ( ‘implode’ , $arr );
return $arr ;
>
heres my version for php4 and below
function str_split_php4 ( $text , $split = 1 )
if (! is_string ( $text )) return false ;
if (! is_numeric ( $split ) && $split < 1 ) return false ;
$len = strlen ( $text );
while ( $i < $len )
$key = NULL ;
for ( $j = 0 ; $j < $split ; $j += 1 )
$key .= $text ;
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).
<?php
function str_rsplit ( $str , $sz )
// splits a string «starting» at the end, so any left over (small chunk) is at the beginning of the array.
if ( ! $sz )
if ( $sz > 0 ) // normal split
$l = strlen ( $str );
$sz = min (- $sz , $l );
$mod = $l % $sz ;
// split
return array_merge (array( substr ( $str , 0 , $mod )), str_split ( substr ( $str , $mod ), $sz ));
>
$str = ‘aAbBcCdDeEfFg’ ;
str_split ( $str , 5 ); // return:
str_rsplit ( $str , 5 ); // return:
str_rsplit ( $str ,- 5 ); // return:
Even shorter version:
//place each character (or group of) of the
string into and array
function str_split_php4($sText, $iSplit = 1)
$iSplit=(integer) $iSplit; // sanity check
if ($iSplit < 1)
$aResult = array();
for($i=0, $limit=strlen($sText); $i < $limit; $i+=$iSplit) $aResult[]=substr($sText, $i, $iSplit);
>
return $aResult;
>
the fastast way (that fits my needs) to replace str_split() in php 4 i found is this:
<?php
if(! function_exists ( ‘str_split’ )) function str_split ( $string , $split_length = 1 ) $array = explode ( «\r\n» , chunk_split ( $string , $split_length ));
array_pop ( $array );
return $array ;
>
>
?>
i also tested the provided functions in the comments..
(the differences are 0.001 to 0.00001 sec)
this function can perform a reverse str_split. I write it for PHP4 but you can rename It for other versions..
if ( !function_exists(‘str_split’) ) function str_split($string,$split_length=1) $sign = (($split_length<0)?-1:1);
$strlen = strlen($string);
$split_length = abs($split_length);
if ( ($split_length==0) || ($strlen==0) ) $result = false;
//$result[] = «»;
>
elseif ($split_length >= $strlen) $result[] = $string;
>
else $length = $split_length;
for ($i=0; $i<$strlen; $i++) $i=(($sign<0)?$i+$length:$i);
$result[] = substr($string,$sign*$i,$length);
$i—;
$i=(($sign<0)?$i:$i+$length);
if ( ($i+$split_length) > ($strlen) ) $length = $strlen-($i+1);
>
else $length = $split_length;
>
>
>
return $result;
>
>
Note that in atleast in PHP 5.5.9 (Zend Engine v2.5.0), str_split with an integer value as an argument may return unpredictable results.
If your number contains leading 0’s, the result array is unprdictable as it may contain any number of digits from the argument or (mostly) just a 0.
Here are a list of possible values that might be returned:
-Interger
<?php
print_r ( str_split (0080450)); // does not work
print_r ( str_split ( strval (0080450))); // neither this
BUT
<?php
print_r ( str_split ( 80450 )); // works fine
print_r ( str_split ( strval ( 80450 ))); // so does this
Floating point numbers have their leading and trailing 0s cut off:
<?php
print_r ( str_split ( 0080450.0010 )); // works but.. print_r(str_split(strval(0080450.0010))); // same here..
I’m not sure if this can be considered a bug, since this is due to how type conversion and casting works, so i just posted it here.
I’ve notced that this is how strval() works. Can anyone shed light into this.
Here is a better version of queremy@gmail.com’s solution. It has the exact same interface as str_split, but works with any UTF-8 string.
<?php
if (! function_exists ( ‘mb_str_split’ )) /**
* Converts an UTF-8 string to an array.
*
* E.g. mb_str_split(«Hello Friend»);
* returns [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’]
*
* @param string $string The input string.
* @param int $split_length Maximum length of the chunk. If specified, the returned array will be broken down
* into chunks with each being split_length in length, otherwise each chunk will be one character in length.
* @return array|boolean
* —
* — If the split_length length exceeds the length of string, the entire string is returned
* as the first (and only) array element.
* — False is returned if split_length is less than 1.
*/
function mb_str_split ( $string , $split_length = 1 )
if ( $split_length == 1 ) return preg_split ( «//u» , $string , — 1 , PREG_SPLIT_NO_EMPTY );
> elseif ( $split_length > 1 ) $return_value = [];
$string_length = mb_strlen ( $string , «UTF-8» );
for ( $i = 0 ; $i < $string_length ; $i += $split_length ) $return_value [] = mb_substr ( $string , $i , $split_length , «UTF-8» );
>
return $return_value ;
> else return false ;
>
>
>
?>
For those who work with PHP < 5:
if (! function_exists ( «str_split» )) function str_split ( $string , $length = 1 ) if ( $length <= 0 ) trigger_error ( __FUNCTION__ . «(): The the length of each segment must be greater then zero:» , E_USER_WARNING );
return false ;
>
$splitted = array();
$str_length = strlen ( $string );
$i = 0 ;
if ( $length == 1 ) while ( $str_length —) $splitted [ $i ] = $string [ $i ++];
>
> else $j = $i ;
while ( $str_length > 0 ) $splitted [ $j ++] = substr ( $string , $i , $length );
$str_length -= $length ;
$i += $length ;
>
>
return $splitted ;
>
>
A good way to use this method to convert CamelCase text into nice text would be-
<?php
/**
Returns a formatted string based on camel case.
e.g. «CamelCase» -> «Camel Case».
*/
function FormatCamelCase ( $string ) $output = «» ;
foreach( str_split ( $string ) as $char ) strtoupper ( $char ) == $char and $output and $output .= » » ;
$output .= $char ;
>
return $output ;
>
?>
how I can conwert
$string
‘1, 2, 5, 6, 10, 13, 23’
from ENUM at mySQL to
<?php
function enum_to_array ( $psEnum )
$aReturn = array();
$aTemp = explode ( ‘, ‘ , $psEnum );
for ( $i = $aTemp [ 0 ]; $i <= $aTemp [ count ( $aTemp )- 1 ]; $i ++)
$aReturn [ $i ] = in_array ( $i , $aTemp );
>
>
?>
I was looking for a function that would split a string into an array like str_split() and found Razor’s function above. Just though that I would simplify the code a little.
<?php
function str_split_php4 ( $text , $split = 1 ) //place each character of the string into and array
$array = array();
for( $i = 0 ; $i < strlen ( $text ); $i ++) $key = NULL ;
for ( $j = 0 ; $j < $split ; $j ++) $key .= $text [ $i ];
>
array_push ( $array , $key );
>
return $array ;
>
?>
Both mine and worksRazor’s work well, I just prefer to use less code. I could have written one myself, but I was just being lazy.
Here is what I use. I started with examples here but modified to my own version:
function str_split ( $text , $split = 1 )
if (! is_string ( $text )) return false ;
if (! is_numeric ( $split ) && $split < 1 ) return false ;
$len = strlen ( $text );
$array = array();
$s = 0 ;
$e = $split ;
while ( $s < $len )
$e =( $e < $len )? $e : $len ;
$array [] = substr ( $text , $s , $e );
$s = $s + $e ;
>
return $array ;
>
>
?>
If you use PHP 4 and don’t need the split_length parameter, here’s the shortest replacement:
If you pass 0 as the second argument, then an error occurs
ValueError : str_split(): Argument #2 ($length) must be greater than 0
<?
//fast & short version od str_split
function string_split($str)
$str_array=array();
$len=strlen($str);
for($i=0;$i<$len;$i++) $str_array[]=$str;
return $str_array;
>
//example :
var_dump (string_split(«split this»));
?>
I think that the last post by carlosreche at yahoo dot com is too complicated.
It’s much easier if you do it like this:
<?php
if (! function_exists ( «str_split» )) function str_split ( $str , $length = 1 ) if ( $length < 1 ) return false ;
$strlen = strlen ( $str );
$ret = array();
for ( $i = 0 ; $i < $strlen ; $i += $length ) $ret [] = substr ( $str , $i , $length );
>
return $ret ;
>
>
?>
I hope it helps for those with PHP <5
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.
// cloackEmail() accepts a string, the email address to be cloaked
function cloakEmail ( $email )
// We create a new array called $arChars, which will contain the individula characters making up the email address. The array is blank for now.
$arChars = array();
// We extract each character from the email ‘exploiting’ the fact that strings behave like an array: watch the ‘$email[$i]’ bit, and beging to fill up the blank array $arChars
for ( $i = 0 ; $i < strlen ( $email ); $i ++)
// Now we work on the $arChars array: extract each character in the array and print out it’s ASCII value prefixed with ‘&#’ to convert it into an HTML entity
foreach ( $arChars as $char )
// The result is an email address in HTML entities which, I hope most email address harvesters can’t read.
PHP: Split string [duplicate]
How do I split a string by . delimiter in PHP? For example, if I have the string «a.b» , how do I get «a» ?
7 Answers 7
You can also directly fetch parts of the result into variables:
If you know your string has a fixed number of components you could use something like
![]()
![]()
![]()
The following will return you the «a» letter:
![]()
![]()
Returns an array of split elements.
To explode with ‘.’, use:
![]()
-
The Overflow Blog
Linked
Related
Hot Network Questions
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.13.43305
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.