Ryan Cooper
Ryan Cooper

Reputation: 703

Capitalize every other letter within exploded array

Initially i had posted a question to find a solution to capitalize every other letter in a string. Thankfully Alex @ SOF was able to offer a great solution, however ive been unable to get it to work with an array... To be clear what im trying to do in this case is explode quotes, capitalize every other letter in the array then implode them back.

if (stripos($data, 'test') !== false) {
$arr = explode('"', $data);

$newStr = '';
foreach($arr as $index => $char) {
$newStr .= ($index % 2) ? strtolower($char) : strtoupper($char);
}

$data = implode('"', $arr);
}

Upvotes: 1

Views: 629

Answers (3)

hypervisor666
hypervisor666

Reputation: 1275

Or.... instead of using regular expression you could just not even use the explode method, and go with every other character and capitalize it. Here is an example:

$test = "test code here";

        $count = strlen($test);
        echo "Count = " . $count . '<br/>';
        for($i = 0; $i < $count; $i++)
        {
            if($i % 2 == 0)
            {
                $test[$i] = strtolower($test[$i]);
            }
            else 
            {
                $test[$i] = strtoupper($test[$i]);
            }
        }
        echo "Test = " . $test;

The secret lies in the modulus operator. ;)

Edit: Dang, I just noticed the post above me by Jordan Arsenault already submitted this answer... I got stuck on the regex answer I missed that :-/ sorry Jordan, you were already on point.

Upvotes: 1

alex
alex

Reputation: 490123

Using the anonymous function requires >= PHP 5.3. If not, just make the callback a normal function. You could use create_function(), but it is rather ugly.

$str = '"hello" how you "doing?"';

$str = preg_replace_callback('/"(.+?)"/', function($matches) {
  $newStr = '';
   foreach(str_split($matches[0]) as $index => $char) {
       $newStr .= ($index % 2) ? strtolower($char) : strtoupper($char);
   }
   return $newStr;

}, $str);

var_dump($str);

Output

string(24) ""hElLo" how you "dOiNg?""

CodePad.

If you want to swap the case, swap the strtolower() and strtoupper() calls.

Upvotes: 3

Jordan Arsenault
Jordan Arsenault

Reputation: 7388

Is this what you're looking for?

 foreach($data as $key => $val)
    {
       if($key%2==0) $data[$key] = strtoupper($data[$key]);
       else $data[$key] = strtolower($data[$key]);
    }

Upvotes: 2

Related Questions