Reverse string without strrev

前端 未结 23 964
忘了有多久
忘了有多久 2020-12-13 13:19

Some time ago during a job interview I got the task to reverse a string in PHP without using strrev.

My first solution was something like this:

相关标签:
23条回答
  • 2020-12-13 14:21

    Try this:

    $s = 'abcdefg';
    
    for ($i = strlen($s)-1; $i>=0; $i--) {
           $s .= $s[$i];
           $s[$i] = NULL;
     }
    var_dump(trim($s));
    
    0 讨论(0)
  • 2020-12-13 14:22

    Here it is PHP7 version of this:

    echo "\u{202E}abcdefg"; // outs: gfedcba
    
    0 讨论(0)
  • 2020-12-13 14:22
    //Reverse String word by word
    $str = "Reverse string word by word";
    $i = 0;
    while ($d = $str[$i]) {
        if($d == " ") {
            $out = " ".$temp.$out;
            $temp = "";
        }
        else
            $temp .= $d;
    
        $i++;
    }
    echo $temp.$out;
    
    0 讨论(0)
  • 2020-12-13 14:23

    you could use substr with negative start.

    Theory & Explanation

    you can start with for loop with counter from 1 to length of string, and call substr inside iteration with counter * -1 (which will convert the counter into negative value) and length of 1.

    So for the first time counter would be 1 and by multiplying with -1 will turn it to -1

    Hence substr('abcdefg', -1, 1); will get you g
    and next iteration substr('abcdefg', -2, 1); will get you f
    and                       substr('abcdefg', -3, 1); will get you e
    and so on ...

    Code

    $str = 'abcdefghijklmnopqrstuvwxyz';
    for($i=1; $i <= strlen($str); $i++) {
        echo substr($str, $i*-1, 1);
    }
    

    In Action: https://eval.in/583208

    0 讨论(0)
  • 2020-12-13 14:23
       <?php
         $value = 'abcdefg';
         $length_value = strlen($value);
         for($i = $length_value-1; $i >=0 ;$i--){    
           echo $value[$i];
         }
       ?>
    
    0 讨论(0)
提交回复
热议问题