Here a sample code:
<?php
$temp_files = array("_temp15.txt","temp10.txt", "temp1.txt","temp22.txt","_temp2.txt");
natsort($temp_files);
print_r($temp_files);
?>
Actual output:
[4] => _temp2.txt
[0] => _temp15.txt
[2] => temp1.txt
[1] => temp10.txt
[3] => temp22.txt
Desired output:
[2] => temp1.txt
[4] => _temp2.txt
[1] => temp10.txt
[0] => _temp15.txt
[3] => temp22.txt
In other words, I want to execute a natural sort ignoring a given (but optional) prefix. In this case the optional prefix is _
.
In my use-case scenario the filenames are unique, regardless if the prefix is present or not. I.e. temp1.txt
and _temp1.txt
are NOT allowed.
The ugly solution I found is:
- cycle among all items and store the keys with the prefix
- remove the prefix from the array
- sort the array
- restore the prefix using the keys collected at point 1
Is there something better than this brute force approach?
CodePudding user response:
uasort
with a custom comparison callback, that uses strnatcmp
. Then you can strip off any _
prefixes, before you pass the two values to compare to strnatcmp.
uasort($temp_files, function($a, $b) {
return strnatcmp(ltrim($a, '_'), ltrim($b, '_'));
});
Edit: Replaced usort
with uasort
, to maintain the keys.