PDA

View Full Version : Building Script that makes TeXt LiKe ThIs


Arnack
07-01-2008, 06:25 PM
Hello, I am currently working on a script to help me practice with my general coding and what I plan on doing is having a string and then capitalizing and lower casing the letters in my string (So SoMeThInG lIkE tHiS). Here is my code so far and all it outputs is "hello worlD"

<?
$string="Hello World";
$num=0;
$num2=1;
while ($num < 10) {
$string[$num]=strtolower($string[$num]);
$string[$num2]=strtoupper($string[$num2]);
$num++;
$num2++;
}
echo $string;
?>

ohgod
07-01-2008, 07:29 PM
this tries to use php5's str_split function, and fakes it if php4 is being used
<?

$string = "Hello World";
$case = 0;
$result = "";


if(!function_exists('str_split')) {
function str_split($string, $split_length = 1) {

$array = explode("\r\n", chunk_split($string, $split_length));
array_pop($array);
foreach($array as $value){
if($case == 0){
$case = 1;
$value = strtoupper($value);
$result .= $value;
}elseif($case == 1){
$case = 0;
$value = strtolower($value);
$result .= $value;
}
}

return $result;
}
}else{
foreach($array as $value){
if($case == 0){
$case = 1;
$value = strtoupper($value);
$result .= $value;
}elseif($case == 1){
$case = 0;
$value = strtolower($value);
$result .= $value;
}
}
return $result;
}

$result = str_split($string);

echo $result;




?>


echos HeLlO WoRlD

kbluhm
07-01-2008, 07:32 PM
Oh God, that is a lot of code. ;)

Give this function a look. It will only uppercase and lowercase letters, which is obvious... but to be more specific, non-alpha characters will not affect the next letter's case (pay attention to the digits and spaces in the examples). Basically, you won't have a lower/uppercase letter on either side of a non-letter:

function mixed_caps( $input, $upper = TRUE )
{
$upper = ( bool ) $upper;
for ( $i = 0, $len = strlen( $input ); $i < $len; $i++ )
{
if ( ctype_alpha( $input[$i] ) )
{
$input[$i] = $upper ? strtoupper( $input[$i] ) : strtolower( $input[$i] );
$upper = ! $upper;
}
}
return $input;
}

Usage:

// I wIlL bE rUnNiNg 2 MaRaThOnS oN tHe 16Th Of NoVeMbEr.
echo mixed_caps( 'I will be running 2 marathons on the 16th of November.' );

// i WiLl Be RuNnInG 2 mArAtHoNs On ThE 16tH oF nOvEmBeR.
echo mixed_caps( 'I will be running 2 marathons on the 16th of November.', FALSE );