How to move the digits of a string with digits and letters to the beginning of the string in PHP

1 Answer

0 votes
function moveDigitsToFront($input) {
    // Separate digits and non-digits using preg_match_all
    preg_match_all('/\d/', $input, $digits); // Extract digits
    preg_match_all('/\D/', $input, $nonDigits); // Extract non-digits

    // Combine digits and non-digits
    $result = implode('', $digits[0]) . implode('', $nonDigits[0]);

    return $result;
}

$input = "d2c54aeb31";
$output = moveDigitsToFront($input);

echo $output; 

 
 
/*
run:
 
25431dcaeb
 
*/

 



answered May 27, 2025 by avibootz
...