如何根据str len-php对file.txt行进行排序

时间:2011-08-06 18:28:37

标签: php

我想根据字符串len

对file.txt进行排序

示例file.txt:

wew
12dde
12swsw
11
swsw
a

of sort文件sorted.txt:

a
11
wew
swsw
12dde
12swsw

2 个答案:

答案 0 :(得分:4)

$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);

输出:

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"
}

答案 1 :(得分:1)

这应该做你需要的:

<?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'));