0

I want to order a string so that the capital letters come first. To make it harder it would be nice to follow the pattern of another variable.

Lets say I have

$x = "FAcfAC";

and I want to order this firstly in the order of characters in

$y = "FAC";

then with the capital letter first, so that the result is

$result = "FfAACc"
wigeon
  • 57
  • 1
  • 5
  • Split the string into an array using str_split(), use one of the many array sorting methods to sort by the values of another array (e.g. http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array), then rebuild the string using implode – Mark Baker Sep 04 '14 at 18:38

1 Answers1

0

Something like this, the only downside is that if the character is not included in $y it will be excluded from the original string.

<?php

$x = 'FAcfAC';
$y = 'FAC';
$result = '';

$yLength = strlen($y);

for ($i = 0; $i < $yLength; $i++)
{
    $char = $y{$i};
    $upper = strtoupper($char);
    $lower = strtolower($char);

    if ($count = substr_count($x, $upper))
    {
        $result .= str_repeat($upper, $count);
    }

    if ($count = substr_count($x, $lower))
    {
        $result .= str_repeat($lower, $count);
    }
}

echo $result;
sikhlana
  • 95
  • 7