skip to Main Content

Say I have a string

"example1string"

I would like to turn it into

"1examplestring"

I am experimenting with methods to be able to reorder an array of strings by number using the natsort() method, however it doesn’t seem to work correctly when the number is in the middle of the string.

I have searched for a solution but have so far found nothing with this specific issue.

2

Answers


  1. I’m sure there is a more efficient regex but here’s a greedy way:

    $str = 'example1string';
    
    $new_str = preg_replace("@(.*?)([0-9]+)(.*|$)@", "$2$1$3", $str);
    
    echo $new_str;
    
    Login or Signup to reply.
  2. Try the below PHP function, Please note that as Rob asked in the comment, what happens when a string has multiple digits
    like wwehehejr21jfkr44j with the below example the outcome will be 2144wwehehejrjfkrj

    Your question also had said reorder, did you mean if a string is wwehehejr21jfkr44j the output should be 1244wwehehejrjfkrj ?

    
    function moveNumbersToFront($inputString) {
        // Separate numbers and non-numbers
        preg_match_all('/d+|D+/', $inputString, $matches);
    
        // Concatenate all numbers followed by non-numbers
        $result = implode('', $matches[0]);
    
        return $result;
    }
    
    //usage:
    $inputString = "ww9ehehejr21jfkr44j";
    $outputString = moveNumbersToFront($inputString);
    echo $outputString; //92144wwehehejrjfkrj
    
    

    Okay now if you meant that if a if a string like wwehehejr21jfkr44j is given the output should be 1244wwehehejrjfkrj then use the below code by adding the sort like below:

    
    function orderNumbers($inputString) {
        
        preg_match_all('/d+|D+/', $inputString, $matches);
    
        // Get and sort the numbers
        $numbers = $matches[0];
        sort($numbers);
    
        $result = implode('', $numbers);
    
        return $result;
    }
    
    

    Good luck, Amigo!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search