0
0

More than 3 years have passed since last update.

文字列の長い順番に揃えたい

Posted at

たとえばtwitterのツイートの中のユーザIDをリンクにしたいとき
@hoge, @hogehoge があると、@hogeを置換するときに@hogehogeのほうも置換されちゃう
これを防ぐには、ユーザIDを抽出した後に文字数の大きい順番にソートする必要がある

このロジックは文字列置換・文字列探索の業務でちょくちょく必要になる

$ary = ['hogehoge', 'hoge', 'aiueo'];

usort($ary, 'lrsort');

function lrsort ($a, $b) {
    $la = strlen($a);
    $lb = strlen($b);
    if ($la < $lb) return 1;
    if ($la > $lb) return -1;
    return 0;
}
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0