Search code examples
phpreplacereverseoffset

Reverse position of vowels in a string


I want to reverse the order of vowels in a string. I have written the below code, but the result set is empty.

Example -

"hello", return "holle"

"leetcode", return "leotcede"

Help me to achieve this.

<?php
function reverseVowels($string) {

    $result = '';
    
    $string = array();
    $vowels = array();
    
    $strlength = count($string);
    for ($i=0; $i < $strlength; $i++) {
        $orig = $strlength[$i];
        $char =  strtolower($strlength[$i]);

        if ($char === 'a' || $char === 'e' || $char === 'i' || $char === 'o' || $char === 'u') {
            array_push($vowels, $orig);
            $orig = null; 
        }
        
         array_push($string, $orig);
       
    }
    $new_strlength = count($string);
    
    for ($i=0; $i < $new_strlength; $i++) {
        if (!$string[$i]) {
            $string[$i] = array_splice($vowels, count($vowels) - 1, 1);
        }
    }
    
    $result = $string;
    return $result;
  
}

$res = reverseVowels("hello hello");
print_r($res);

//"hello", return "holle"
//"leetcode", return "leotcede"
?>

Solution

  • Here is the changed and working code:

    function reverseVowels($str) {
      $result = '';
        $string = array();
        $vowels = array();
        $strlength = count($str);
        for ($i=0; $i < strlen($str); $i++) {
            $orig = $str[$i];
            $char =  strtolower($str[$i]);
            if ($char === 'a' || $char === 'e' || $char === 'i' || $char === 'o' || $char === 'u') {
                array_push($vowels, $orig);
                $orig = null; 
            }
             array_push($string, $orig);
        }
        $new_strlength = count($string);
        for ($i=0; $i < count($string); $i++) {
            if (!$string[$i]) {
                $string[$i] = array_splice($vowels, count($vowels) - 1, 1)[0];
            }
        }
        $result = $string;
        return $result;
    }
    $res = reverseVowels("leetcode");
    echo "<pre>";
    print_r($res);
    echo "</pre>";