使用PHP按字母顺序对html字符串进行排序


Sort html string in alphabetical order using PHP

请参阅下面的代码。我想按名称而不是id对选项标签进行排序。

这是我的代码:

<?php
$string = '<option id=a1>Sinead Shannon Roche<option id=a2>Emile Abossolo Mbo<option id=a3>Youssouf Djaoro<option id=a4>Dioucounda Koma';
$new_string = '';
$s = explode('<', $string);
asort($s);
foreach($s AS $v) {
    $new_string = $new_string . '<' . $v;
}
// I want $new_string to be "<option id=a4>Dioucounda Koma<option id=a2>Emile Abossolo Mbo<option id=a1>Sinead Shannon Roche<option id=a3>Youssouf Djaoro"
?>

我会自己使用JQuery。。。

如果你有兴趣,这里的代码。

声明全局函数

$.fn.sortSelect = function() {
    var op = this.children("option");
    op.sort(function(a, b) {
        return a.text > b.text ? 1 : -1;
    })
    return this.empty().append(op);
}

并从代码中调用函数。

$("#my_select").sortSelect();