在PHP中更改字符串中每个第n个字母的大小写

时间:2016-08-03 05:01:55

标签: php string

我正在尝试编写一个简单的程序,它在字符串中使用every 4th letter(不是字符)(不计算空格)并将case更改为相反的(如果它&#39} ; s在较低位置,将其更改为高位,反之亦然)。

到目前为止我所拥有的:

echo preg_replace_callback('/.{5}/', function ($matches){
            return ucfirst($matches[0]);   
     }, $strInput);

预期结果: "The sky is blue"应输出"The Sky iS bluE"

3 个答案:

答案 0 :(得分:2)

$str = 'The sky is blue';
    $strArrWithSpace = str_split ($str);
    $strWithoutSpace = str_replace(" ", "", $str);
    $strArrWithoutSpace = str_split ($strWithoutSpace);
    $updatedStringWithoutSpace = '';
    $blankPositions = array();
    $j = 0;
    foreach ($strArrWithSpace as $key => $char) {
        if (empty(trim($char))) {
            $blankPositions[] = $key - $j;
            $j++;
        }
    }

    foreach ($strArrWithoutSpace as $key => $char) {
        if (($key +1) % 4 === 0) {
            $updatedStringWithoutSpace .= strtoupper($char);
        } else {
            $updatedStringWithoutSpace .= $char;
        }

    }

    $arrWithoutSpace = str_split($updatedStringWithoutSpace);
    $finalString = '';
    foreach ($arrWithoutSpace as $key => $char) {
        if (in_array($key, $blankPositions)) {
            $finalString .= ' ' . $char;
        } else {
            $finalString .= $char;
        }
    }

    echo $finalString;

答案 1 :(得分:1)

试试这个:

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

它将字符串

的每个第二个字符大写

答案 2 :(得分:1)

<?php
    $str = "The sky is blue";
    $str = str_split($str);
    $nth = 4; // the nth letter you want to replace
    $cnt = 0;
    for ($i = 0; $i < count($str); $i++) {
        if($str[$i]!=" " && $cnt!=$nth)
            $cnt++;
        if($cnt==$nth)
        {
            $cnt=0;
            $str[$i] = ctype_upper($str[$i])?strtolower($str[$i]):strtoupper($str[$i]);
        }
    }
    echo implode($str);
?>

此代码满足您的所有条件。

修改

我会用

$str = str_replace(" ","",$str);

忽略字符串中的空格。但正如你想要它们在输出中那样,所以不得不应用上面的逻辑。