By the way, you have a slight error in your capitalized string:
$string_1: a4nas60dj71wiena15sdl1131kg12b
$string_2: a4NaS60dJ71wIeNa15Sdl1131Kg12B
^ should be capital so out of sync for rest of string
I'll give you two ways of doing it:
<?php
header('Content-Type: text/plain');
$string_1 = "a4nas60dj71wiena15sdl1131kg12b";
$string_2 = "a4NaS60dJ71wIeNa15Sdl1131Kg12B";
$letter_count = 0;
$result = '';
for ($i=0; $i<strlen($string_1); $i++) {
if (!preg_match('![a-zA-Z]!', $string_1[$i])) {
$result .= $string_1[$i];
} else if ($letter_count++ & 1) {
$result .= strtoupper($string_1[$i]);
} else {
$result .= $string_1[$i];
}
}
$result2 = preg_replace_callback('!([a-zA-Z]\d*)([a-zA-Z])!', 'convert_to_upper', $string_1);
function convert_to_upper($matches) {
return strtolower($matches[1]) . strtoupper($matches[2]);
}
echo "$string_1\n";
echo "$string_2\n";
echo "$result\n";
echo "$result2\n";
?>
Note: The above makes several assumptions:
- Characters other than numbers and letters can be in the string;
- You want to alternate case regardless of the original (eg "ASDF" becomes "aSdF");
- You're capitalizing every second letter, not every second lowercase letter.
The above can be altered if these assumptions are incorrect.