How to reverse an array of characters without affecting the special characters in PHP

1 Answer

0 votes
// Enable strict typing for predictable type safety
declare(strict_types=1);

/**
 * Reverses only the alphabetic characters in a character array in-place,
 * leaving special characters, spaces, and digits in their original positions.
 * 
 * @param array<int, string> $chars Reference to the character array (vector).
 */
function reverseOnlyLetters(array &$chars): void {
    $left = 0;
    $right = count($chars) - 1;

    // Use a two-pointer approach moving inward from both ends
    while ($left < $right) {
        // Advance left pointer until it points to an alphabetic character
        while ($left < $right && !ctype_alpha($chars[$left])) {
            $left++;
        }
        
        // Move right pointer backward until it points to an alphabetic character
        while ($left < $right && !ctype_alpha($chars[$right])) {
            $right--;
        }

        // Swap the valid letters found at both pointers
        if ($left < $right) {
            $temp = $chars[$left];
            $chars[$left] = $chars[$right];
            $chars[$right] = $temp;

            $left++;
            $right--;
        }
    }
}

// Input string specified
$inputString = "a#b$%c&*(def!";

// Convert the string into an array of single-character strings (acting as a character vector)
$charVector = str_split($inputString);

echo "Original: " . implode('', $charVector) . PHP_EOL;

// Apply the reversal function in-place
reverseOnlyLetters($charVector);

// Reconstruct and display the final string
echo "Reversed: " . implode('', $charVector) . PHP_EOL;


/*
run:

Original: a#b$%c&*(def!
Reversed: f#e$%d&*(cba!

*/

 



answered 2 days ago by avibootz

Related questions

...