如何对两个内部有4位数字(年份)的字符串进行排序?

时间:2015-04-12 20:17:52

标签: php sorting

我希望每年对两个方面进行排序,以便1920年的声明首先出现,然后是1930年的声明。

首先我用(。)爆炸两个字符串然后我用natsort按年份排序..但它没有用。到目前为止我所做的是:

<?php

$strn="The Muslim League slowly rose to mass popularity in the **1930s** amid fears of under-representation and neglect of Muslims in politics.The largely non-violent independence struggle led by the Indian Congress engaged millions of protesters in mass campaigns of civil disobedience in the **1920s**";

$result = explode('.',$strn);
natsort($result);

echo $result[0];

echo $result[1];
?>

1 个答案:

答案 0 :(得分:3)

这应该适合你:

(这里我只抓住每个字符串中的年份并执行usort()比较字符串并按年份排序)

usort($arr, function($a, $b){
    preg_match("/\d{4}/", $a, $matches);
    $yearOne = $matches[0];
    preg_match("/\d{4}/", $b, $matches);
    $yearTwo = $matches[0];

    if($yearOne == $yearTwo)
        return 0;
    return $yearOne > $yearTwo ? 1 : -1;
});

输出:

Array
(
    [0] => The largely non-violent independence struggle led by the Indian Congress engaged millions of protesters in mass campaigns of civil disobedience in the **1920s**
    [1] => The Muslim League slowly rose to mass popularity in the **1930s** amid fears of under-representation and neglect of Muslims in politics
)

此外,如果您想再次将其打印为字符串,请使用:

echo implode(".", $strn);