我有变量:
$data = "Article 4 Article 2 Article 10";
我需要输出:
Article 2 Article 4 Article 10
我试过这样的事情:
<?php
$data = "Article 4 Article 2 Article 10";
function sort_titles_article_numbers($a,$b) {
$akey = $a->$data;
if (preg_match('/^Article (\d+)\. /', $akey, $matches)) {
$akey = $matches[1];
}
$bkey = $b->$data;
if (preg_match('/^Article (\d+)\. /', $bkey, $matches)) {
$bkey = $matches[1];
}
if ($akey == $bkey) {
return 0;
}
return ($akey < $bkey) ? -1 : 1;
}
uasort($data,'sort_titles_article_numbers');
echo $data;
?>
但是有些不对劲。似乎uasort只适用于数组,但我如何在变量中对它进行排序?
答案 0 :(得分:3)
$data = "Article 4 Article 2 Article 10";
// line below splits string by number, keeping it, and trims elements of array
$tmp = array_map('trim', preg_split('/\d+\K/', $data));
natsort($tmp); // very useful function for 'natural' sorting
echo join(' ', $tmp); // converts array to string
结果 - Article 2 Article 4 Article 10
答案 1 :(得分:0)
如果你想只优先考虑数字,我找到了一种更好的数字排序方法:
$data = "Artihcle 4 Artizcle 2 Article 10";
$tmp = preg_split('/\w \d+\K/', $data);
usort($tmp, function ($a, $b) {
preg_match('/\d+$/', $a, $matchA);
preg_match('/\d+$/', $b, $matchB);
return $matchA[0] - $matchB[0];
});
$data2 = join(' ', $tmp);
echo trim($data2);