how to sort lines of file.txt according to str len - php
i want to sort a file.txt according to string len
sample file.txt :
wew
12dde
12swsw
11
swsw
a
ofter 开发者_如何学运维sort file sorted.txt :
a
11
wew
swsw
12dde
12swsw
$string = <<<EOT
wew
12dde
12swsw
11
swsw
a
EOT;
$array = explode("\n", $string);
usort($array, function($a, $b) { return strlen($a) - strlen($b); });
var_dump($array);
Output:
array(6) {
[0]=>
string(1) "a"
[1]=>
string(3) "11"
[2]=>
string(4) "wew"
[3]=>
string(5) "swsw"
[4]=>
string(6) "12dde"
[5]=>
string(7) "12swsw"
}
This should do what you need:
<?php
function lensort($a, $b) {
return strlen($a) - strlen($b);
}
$path1 = '/root/oldfile.txt';
$path2 = '/root/newfile.txt';
file_put_contents($path2, usort(file($path1), 'lensort'));
精彩评论