简体   繁体   中英

Change case of every nth letter in a string in PHP

I am trying to write a simple program which takes every 4th letter (not character) in a string (not counting spaces) and changes the case to it's opposite (If it's in lower, change it to upper or vice versa).

What I have so far:

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

Expected Result: "The sky is blue" should output "The Sky iS bluE"

$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;

Try this:

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

it capitalize every 2nd character of string

<?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);
?>

This code satisfies all of your conditions.

Edit:

I would have used

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

to ignore the whitespaces in the string. But as you want them in the output as it is, so had to apply the above logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM