Search code examples
phpstringnumbers

Find numbers on a string and order by them


I have this string

$s = "red2 blue5 black4 green1 gold3";

I need to order by the number, but can show the numbers. Numbers will always appears at the end of the word. the result should be like:

$s = "green red gold black blue";

Thanks!


Solution

  • $s = "red2 blue5 black4 green1 gold3";
    $a=[];
    preg_replace_callback('/[a-z0-9]+/',function($m) use (&$a){
        $a[(int)ltrim($m[0],'a..z')] = rtrim($m[0],'0..9');
    },$s);
    ksort($a);
    print " Version A: ".implode(' ',$a);
    
    $a=[];
    foreach(explode(' ',$s) as $m){
        $a[(int)ltrim($m,'a..z')] = rtrim($m,'0..9');
    }
    ksort($a);
    print " Version B: ".implode(' ',$a);
    
    preg_match_all("/([a-z0-9]+)/",$s,$m);
    foreach($m[1] as $i){
        $a[(int)substr($i,-1,1)] = rtrim($i,'0..9');
    }
    ksort($a);
    print " Version C: ".implode(' ',$a);
    

    Use one of them, but also try to understand whats going on here.