Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » Split String Per Character

Split String Per Character

Use this function to split a string per character. The function takes the string and a line ending as parameters.

Use this function to split a string per character.


function outputString($str, $line_end) 
    // Set the variable that holds the string
    $str = "";

    // Use a for loop to grab each character
    for ($i = 0; $i < strlen($str); $i++) 
		// This line cuts the string one character at a time
        $str .= substr($str, $i , 1) . $line_end;

    // Return the '$str' variable
    return $str;

// Here is the string we want to affect
$text = "This is an example string!";

// Finally print out the string 
print outputString($text, "
"); ?>

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Split String Per Character

 cixent  Wed Nov 24, 2010 5:23 pm  
I want to split

$text = "abcdefgh";


$text[0] = "a";
$text[1] = "b";
$text[2] = "c";
so on...

 mkeefe  Wed Nov 24, 2010 11:06 pm  
@cixent - In order to split a string into an array you would use the str_split() function. Here is an example using your sample string.


$text = "abcdefgh";
$text_split = str_split($text);



This would produce the following result:

[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => g
[7] => h

For more powerful string splitting you could use preg_split but not for simple matching, such as above.

Hope that helps.
Add a comment
The ability to add new comments has been disabled in this archived version.

Main | Tutorials | Articles