Looping through a string character by character line by line
Okay, please ignore the relics like wild_colors ... etc. The main point is how to loop through a string, in this case a string that contains line endings \n and displays it's characters one by one.
The reason for the relics, is I was creating a script that would create a with a random color for every non space character in a string. It was just for fun.
Here's the code,
<?php
$str = <<<eof
Hello World from the pretty colors.
eof;
### Use wild_colors($str,TRUE) for black and white grayscale or
### wild_colors($str) for colors.
function wild_colors($str,$black_and_white=FALSE)
{
$str = preg_replace("/\r/","",$str);
$a_str = explode("\n",$str);
$output = "";
foreach($a_str as $line)
{
for($i=0;$i<strlen($line);$i++)
{
if($black_and_white)
{
$rand = rand(0,255);
$random_color = "rgb({$rand},{$rand},{$rand})";
}
else
{
$random_color = "rgb(".rand(0,255).",".rand(0,255).",".rand(0,255).")";
}
$output .= "<span style=\"color:{$random_color}\">".substr($line,$i,1)."</span>";
}
$output .= "<br />\n";
}
unset($a_str);
return $output;
}
print(wild_colors($str,true));
?>
$str = <<<eof
Hello World from the pretty colors.
eof;
### Use wild_colors($str,TRUE) for black and white grayscale or
### wild_colors($str) for colors.
function wild_colors($str,$black_and_white=FALSE)
{
$str = preg_replace("/\r/","",$str);
$a_str = explode("\n",$str);
$output = "";
foreach($a_str as $line)
{
for($i=0;$i<strlen($line);$i++)
{
if($black_and_white)
{
$rand = rand(0,255);
$random_color = "rgb({$rand},{$rand},{$rand})";
}
else
{
$random_color = "rgb(".rand(0,255).",".rand(0,255).",".rand(0,255).")";
}
$output .= "<span style=\"color:{$random_color}\">".substr($line,$i,1)."</span>";
}
$output .= "<br />\n";
}
unset($a_str);
return $output;
}
print(wild_colors($str,true));
?>
[Click to add or edit comments])
Please prepend comments below including a date