Search code examples
phpregexstringcapitalize

how to CaPiTaLiZe every other character in php?


I want to CaPiTaLiZe $string in php, don't ask why :D

I made some research and found good answers here, they really helped me. But, in my case I want to start capitalizing every odd character (1,2,3...) in EVERY word.

For example, with my custom function i'm getting this result "TeSt eXaMpLe" and want to getting this "TeSt ExAmPlE". See that in second example word "example" starts with capital "E"?

So, can anyone help me? : )


Solution

  • Here's a one liner that should work.

    preg_replace('/(\w)(.)?/e', "strtoupper('$1').strtolower('$2')", 'test example');
    

    http://codepad.org/9LC3SzjC