Home > Software engineering >  PHP: How to sort the characters according to the order they came out
PHP: How to sort the characters according to the order they came out

Time:02-19

I have string to be separated between vowels and consonants make them lower and ignore white space. sort by character according to the order they came out.

example string :

Sample Case  

my output is :

vowels     : aeae  
consonants : smplcs

my expectation output is :

vowels     : aaee  
consonants : ssmplc
function sortCharacter($chars){
    $chars  = strtolower($chars);
    $chars  = str_replace(' ','',$chars);
    $chars2 = str_split($chars);

    $vowels = ['a','e','i','o','u'];
    $v=[];
    $c=[];
    for ($i=0; $i < count($chars2) ; $i  ) {
        if (in_array($chars2[$i], $vowels)) {
            array_push($v, $chars2[$i]);
        }else{
            array_push($c, $chars2[$i]);
        }

    }


    
    echo "Vowel Character : <br>" ;     
    echo implode("", $v)."<br>";  
    echo "Consonant Character : <br>" ;     
    echo implode("", $c);
    
}

CodePudding user response:

$text = 'Sample Case';

$vowels = '';
foreach (array_count_values(str_split(preg_replace('/[bcdfghjklmnpqrstvwxyz ]/', '', strtolower($text)))) as $k => $v) {
  $vowels .= str_repeat($k, $v);
}

$consonants = '';
foreach (array_count_values(str_split(preg_replace('/[aeiou ]/', '', strtolower($text)))) as $k => $v) {
  $consonants .= str_repeat($k, $v);
}

print_r($vowels);
echo "\n";
print_r($consonants);

Output:

aaee
ssmplc
  •  Tags:  
  • php
  • Related