suche nach in der

str_word_count> <str_shuffle
Last updated: Fri, 18 May 2012

view this page in

str_split

(PHP 5)

str_splitKonvertiert einen String in ein Array

Beschreibung

array str_split ( string $string [, int $split_length = 1 ] )

Konvertiert einen String in ein Array.

Parameter-Liste

string

Die Eingabezeichenkette.

split_length

Maximale Länge eines Teilstücks.

Rückgabewerte

Wenn der optionale Parameter split_length angegeben ist, enthält das zurückgegebene Array Elemente mit der in split_length definierten Länge, andernfalls enthält jedes Element ein einzelnes Zeichen.

FALSE wird zurückgegeben, wenn split_length kleiner als 1 ist. Wenn der Parameter split_length größer als string ist, wird der gesamte String als ein erstes (und einziges) Array-Element zurückgegeben.

Beispiele

Beispiel #1 Beispiel für die Verwendung von str_split()

<?php

$str 
"Hallo Freund";

$arr1 str_split($str);
$arr2 str_split($str3);

print_r($arr1);
print_r($arr2);

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [0] => H
    [1] => a
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => e
    [9] => u
    [10] => n
    [11] => d
)

Array
(
    [0] => Hal
    [1] => lo
    [2] => Fre
    [3] => und
)

Siehe auch

  • chunk_split() - Zerlegt einen String in Teile gleicher Länge
  • preg_split() - Zerlegt eine Zeichenkette anhand eines regulären Ausdrucks
  • explode() - Teilt einen String anhand einer Zeichenkette
  • count_chars() - Gibt Informationen über die in einem String enthaltenen Zeichen zurück
  • str_word_count() - Gibt Informationen über in einem String verwendete Worte zurück
  • for



add a note add a note User Contributed Notes
str_split
Siemen Paulsen
11-Jul-2007 09:46
Meercat9--

Look at the str_split() function.
l0c4lh0st DOT nl AT gmail DOT com
12-Jun-2007 02:28
how I can conwert
$string
 '1, 2, 5, 6, 10, 13, 23'
from ENUM at mySQL to

$array
[0] -> false
[1] -> true
[2] -> true
[3] -> false
[4] -> false
[5] -> true
[6] -> true
[7] -> false
[8] -> false
[9] -> false
[10] -> true
[11] -> false
[12] -> false
[13] -> true
[14] -> false
[15] -> false
...
[23] -> true

<?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);
    }
}
?>
dhayes
07-Jun-2007 09:17
@razor: this'll work for php4
<?php
$str
= 'two words';
$array = explode("\r\n", chunk_split($str,1));
?>
M@rek (from Poland)
27-May-2007 04:25
how I can conwert
$string
 '1, 2, 5, 6, 10, 13, 23'
from ENUM at mySQL to

$array
[0] -> false
[1] -> true
[2] -> true
[3] -> false
[4] -> false
[5] -> true
[6] -> true
[7] -> false
[8] -> false
[9] -> false
[10] -> true
[11] -> false
[12] -> false
[13] -> true
[14] -> false
[15] -> false
...
[23] -> true
Razor
10-May-2007 09:02
heres my version for php4 and below

<?php

function str_split_php4($text, $split = 1)
{
    if (!
is_string($text)) return false;
    if (!
is_numeric($split) && $split < 1) return false;
   
   
$len = strlen($text);
   
   
$array = array();
   
   
$i = 0;
   
    while (
$i < $len)
    {
       
$key = NULL;
       
        for (
$j = 0; $j < $split; $j += 1)
        {
           
$key .= $text{$i};
           
           
$i += 1;   
        }
       
       
$array[] = $key;
    }
   
    return
$array;
}

?>
26-Feb-2007 05:32
Problem with the post below me is, that the string can not contain the splitter "-1-".

Btw, here's my version.
<?php
function strsplit($str, $l=1) {
    do {
$ret[]=substr($str,0,$l); $str=substr($str,$l); }
    while(
$str != "");
    return
$ret;
}
?>
webmaster at nsssa dot ca
28-Oct-2006 04:45
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.

<?php

//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);
     
}

?>
05-Oct-2006 02:14
//fast & short version od str_split PHP3, 4x
function string_split($str, $nr){    
    return split("-l-", chunk_split($str, $nr, '-l-'));
}
//example :
print_r(string_split('123412341234', 4));
ference at super_delete_brose dot co dot uk
31-Aug-2006 09:22
If you are looking for a way to split multibyte strings then this may come in handy:

<?php
$text 
= "süpérbrôsé";

function
mb_str_split($str, $length = 1) {
  if (
$length < 1) return FALSE;

 
$result = array();

  for (
$i = 0; $i < mb_strlen($str); $i += $length) {
   
$result[] = mb_substr($str, $i, $length);
  }

  return
$result;
}

$solo = mb_str_split($text);
$quintet = mb_str_split($text, 5);

print_r($solo);
print_r($quintet);
?>

Spits out:

Array
(
    [0] => s
    [1] => ü
    [2] => p
    [3] => é
    [4] => r
    [5] => b
    [6] => r
    [7] => ô
    [8] => s
    [9] => é
)
Array
(
    [0] => süpér
    [1] => brôsé
)
fstorm2 at gmail dot com
29-Aug-2006 11:08
If you use PHP 4 and don't need the split_length parameter, here's the shortest replacement:

<?php

preg_split
('#(?<=.)(?=.)#s', $str);

?>
http://www.matt-fletcher.co.uk/
21-Aug-2006 01:44
A simple way to split credit card numbers into chunks of four numbers:

<?php
echo implode(' ',str_split($card_number,4));
?>
malmsteenforce at tlen dot pl
20-Jul-2006 07:52
<?
//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{$i};
        return
$str_array;
       }
//example :
var_dump (string_split("split this"));
?>
user at mockme dot com
25-Mar-2006 02:53
found this great example on a php board for those not using php5, as an alternative to the posts below this

<?php
if(!function_exists('str_split')){
    function
str_split($string,$split_length=1){
       
$count = strlen($string); 
        if(
$split_length < 1){
            return
false
        } elseif(
$split_length > $count){
            return array(
$string);
        } else {
           
$num = (int)ceil($count/$split_length); 
           
$ret = array(); 
            for(
$i=0;$i<$num;$i++){ 
               
$ret[] = substr($string,$i*$split_length,$split_length); 
            } 
            return
$ret;
        }     
    } 
}
?>
simple
16-Mar-2006 04:54
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();
        while (strlen($string) > 0) {
            $splitted[] = substr($string, 0, $length);
            $string = substr($string, $length);
        }
        return $splitted;
    }
}
14-Mar-2006 02:49
Note to function by carlosreche at yahoo dot com.

The while:
<?php
...
               while (
$str_length--) {
                  
$splitted[$i] = $string[$i++];
               }
...
?>
.. result in index starting at 1.
Ie: str_split("ABC") gives
Array
(
    [1] => A
    [2] => B
    [3] => C
)
While php5's str_split("ABC") gives
Array
(
    [0] => A
    [1] => B
    [2] => C
)
And his str_split("ABC",2) gives index starting at 0.
Change to this (or something similar):
<?php
...
               while (
$str_length--) {
                  
$splitted[$i] = $string[$i];
                  
$i++;
               }
...
?>
.... or use heavyraptor's function. A bit more sclick,..
heavyraptor
10-Mar-2006 11:07
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
carlosreche at yahoo dot com
15-Feb-2006 01:23
For those who work with PHP < 5:

<?php

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;
    }
}

?>
Hage Yaapa
04-Feb-2006 03:27
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.

<?php

// 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++) { $arChars[] = $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) { print '&#'.ord($char); }

// 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 ######

<?php
function cloakEmail($email) {
   
$arChars = array();
    for (
$i = 0; $i < strlen($email); $i++) { $arChars[] = $email[$i]; }
    foreach (
$arChars as $char) { print '&#'.ord($char); }
}
print
cloakEmail('someone@nokikon.com');
?>

In creating this little utility, I demonstrated how the lack of str_split() can be made up in PHP < 5. If you got how it was accomplished, you could write a function to do exactly what str_split() does in PHP 5 and even name it 'str_split()'. :)
organek at hektor dot umcs dot lublin dot pl
21-May-2005 01:57
[Editor's Note: Or just: php.net/wordwrap]
This is a little function to split a string into shorter strings with max lenght $n in such way, that it don't split words (it search for spaces), it's usefull for articles or sth.
Result is put in $ttab variable, and function result is number of "pages".

<?php
function divide_text($text, $n, &$ttab) {
   
   
$ttab = array();
   
$l = strlen($text); // text length
   
$cb = 0;    //copy begin from..
   
$p = 0; // parts
   
   
if ($l  <= $n) {
       
$ttab[0] = $text;
        return
1;
    } else {
       
$ctrl = 1;
        while((((
$p-1) * $n) < $l) && ($ctrl < 100)) {
       
$crtl++; // control variable, to protect from infinite loops
       
       
$tmp = substr($text, $cb, $n);
       
       
// we're looking for last space in substring
       
$lastpos = strrpos($tmp," ");   
       
        if ( (
is_bool($lastbool) && !$lastpos) || ( $l - $cb <= $n)) {
           
$ttab[$p] = $tmp;
                       
        } else  {
           
$tmpgood = trim(substr($tmp, 0,$lastpos));  // if they were another spaces at the end..
           
$ttab[$p] = $tmpgood;
           
$cb += $lastpos + 1 ;
           
        };
// if
       
$p++;
        };
//for
       
return $p;
    };
// if
   

} // divide text

?>
aidan at php dot net
20-May-2004 06:53
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat

str_word_count> <str_shuffle
Last updated: Fri, 18 May 2012