Php: How to Sort the Characters in a String

PHP: How to sort the characters in a string?

I would make it an array and use the sort function:

$string = 'bac';

$stringParts = str_split($string);
sort($stringParts);
echo implode($stringParts); // abc

Sort string into alphabetical order

sort() :- Returns TRUE on success or FALSE on failure.
You need to quoting over string like $str = 'cat hat'; and you will get result
Try

$str = 'cat hat';
$sparts = str_split($str);
sort($sparts);
$imp = implode('', $sparts); //aachtt
return $imp; // will be a string

How to sort array of string by length and maintain their keys in PHP?

Use uasort:

uasort — Sort an array with a user-defined comparison function and maintain index association

usort doesn't maintain index associations.

Use it like this:

function sortByLength ($a, $b) {
return strlen($b) - strlen($a);
}

$arr = ['longstring', 'string', 'thelongeststring'];

uasort($arr, 'sortByLength');

print_r($arr);

eval.in demo

This returns:

Array
(
[2] => thelongeststring
[0] => longstring
[1] => string
)

PHP: How to sort the characters should be in the order of first occurrence

$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

PHP sort array via a characters in middle of string

First of all this is obviously going to be a custom comparison; the go-to function for that is usort, which accepts a custom comparison as an argument.

The custom comparison function would be like this:

function customCompare($x, $y) {
$x = explode('R', $x);
$y = explode('R', $y);
if ($x[1] != $y[1]) return $x[1] < $y[1] ? -1 : 1;
return strnatcmp($x[0], $y[0]);
}

See it in action.

How it works

First we split each input string on the character R, producing an array such as ['8.25', '16'] from a string such as '8.25R16'. In each array the second element is the diameter (first sort criterion) and the first is the width (second criterion).

If the diameters are different then we immediately pass judgement based on that.

If the diameters are equal then we use strnatcmp to compare the widths -- this is so that a width of 100 is larger than a width of 20 (a dumb ASCII comparison would produce the opposite result).

How to alphabetically sort a php array after a certain character in a string

Another variant:

usort ($values,
function ($a,$b) {
return strcmp (strstr ($a, '.'), strstr ($b, '.'));
});

this will work for both your arrays, since the comparison uses the part of the string starting at the first '.'

If you want to print them out by groups, I think a good solution would be to first create a suitable data structure and then use it both for sorting and printing:

$values = array ("zercggj.co.uk", "lkjhg.org.au", "qqxze.org.au",
"bfhgj.co.uk", "sdfgh.org.uk");

echo "<br>input:<br>";
foreach ($values as $host) echo "$host<br>";

// create a suitable structure
foreach ($values as $host)
{
$split = explode('.', $host, 2);
$printable[$split[1]][] = $split[0];
}

// sort by domains
asort ($printable);

// output
echo "<br>sorted:<br>";
foreach ($printable as $domain => $hosts)
{
echo "domain: $domain<br>";

// sort hosts within the current domain
asort ($hosts);

// display them
foreach ($hosts as $host)
echo "--- $host<br>";
}

This is a good illustration of how you can benefit from thinking about what you will do with your data as a whole instead on focussing on unconnected sub-tasks (like sorting in that case).

How to sort values with special chars in array?

Solution linked by @Sbls in comments

function compareASCII($a, $b) {
$at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
$bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
return strcmp($at, $bt);
}
uasort($lang, 'compareASCII');

Sorting a list of arrays by its last character in php

usort allows a custom sort function to be passed, so you can do:

usort($string , function($a, $b) {
$aLastChar = substr($a, -1);
$bLastChar = substr($b, -1);

return ($aLastChar < $bLastChar) ? -1 : 1;
});

PHP sort array with special characters

Taken reference from this example:-Sort an array with special characters in PHP

Explanation:-

  1. Get array keys using array_keys() method

  2. Sort keys based on iconv() AND strcmp() functions

  3. Iterated over the sorted key array and get their corresponding value from initial array.Save this key value pair to your resultant array

Do like below:-

<?php

setlocale(LC_ALL, 'sl_SI.utf8');

$a = [
'č' => [12],
'a' => [23],
'š' => [45],
'u' => [56]
];

$index_array = array_keys($a);

function compareASCII($a, $b) {
$at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
$bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
return strcmp($at, $bt);
}

uasort($index_array, 'compareASCII');

$final_array = [];
foreach($index_array as $index_arr){

$final_array[$index_arr] = $a[$index_arr];
}

print_r($final_array);

Output:- https://eval.in/990872

Reference:-

iconv()

strcmp()

uasort



Related Topics



Leave a reply



Submit