how to CaPiTaLiZe every other character in php?

亡梦爱人 提交于 2019-12-06 03:43:14

Here's a one liner that should work.

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

http://codepad.org/9LC3SzjC

Well I would just make it an array and then put it back together again.

<?php

$str = "test example";

$str_implode = str_split($str);

$caps = true;
foreach($str_implode as $key=>$letter){
    if($caps){
        $out = strtoupper($letter);
        if($out <> " ") //not a space character
            $caps = false;
    }
    else{
        $out = strtolower($letter);
        $caps = true;
    }
    $str_implode[$key] = $out;
}

$str = implode('',$str_implode);

echo $str;

?>

Demo: http://codepad.org/j8uXM97o

I would use regex to do this, since it is concise and easy to do:

$str = 'I made some research and found good answers here, they really helped me.';
$str = preg_replace_callback('/(\w)(.?)/', 'altcase', $str);
echo $str;

function altcase($m){
    return strtoupper($m[1]).$m[2];
}

Outputs: "I MaDe SoMe ReSeArCh AnD FoUnD GoOd AnSwErS HeRe, ThEy ReAlLy HeLpEd Me."

Example

Try:

function capitalize($string){
    $return= "";
    foreach(explode(" ",$string) as $w){
        foreach(str_split($w) as $k=>$v) {
            if(($k+1)%2!=0 && ctype_alpha($v)){
                $return .= mb_strtoupper($v);
            }else{
                $return .= $v;
            }
        }
        $return .= " ";
    }
    return $return;
}
echo capitalize("I want to CaPiTaLiZe string in php, don't ask why :D");
//I WaNt To CaPiTaLiZe StRiNg In PhP, DoN'T AsK WhY :D

Edited: Fixed the lack of special characters in the output.

This task can be performed without using capture groups -- just use ucfirst().

This is not built to process multibyte characters.

Grab a word character then, optionally, the next character. From the fullstring match, only change the case of the first character.

Code: (Demo)

$strings = [
    "test string",
    "lado lomidze needs a solution",
    "I made some research and found 'good' answers here; they really helped me."
];  // if not already all lowercase, use strtolower()

var_export(preg_replace_callback('/\w.?/', function ($m) { return ucfirst($m[0]); }, $strings));

Output:

array (
  0 => 'TeSt StRiNg',
  1 => 'LaDo LoMiDzE NeEdS A SoLuTiOn',
  2 => 'I MaDe SoMe ReSeArCh AnD FoUnD \'GoOd\' AnSwErS HeRe; ThEy ReAlLy HeLpEd Me.',
)

For other researchers, if you (more simply) just want to convert every other character to uppercase, you could use /..?/ in your pattern, but using regex for this case would be overkill. You could more efficiently use a for() loop and double-incrementation.

Code (Demo)

$string = "test string";
for ($i = 0, $len = strlen($string); $i < $len; $i += 2) {
    $string[$i] = strtoupper($string[$i]);
}
echo $string;
// TeSt sTrInG
// ^-^-^-^-^-^-- strtoupper() was called here
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!