开发者

php to reverse a string without using loops or builtin functions

How would you write a short php function to reverse a string. The function must:

  • have only one argument
  • not use the built-in function 'st开发者_如何学Crrev' or 'array_reverse'
  • not a use a looping construct like 'for', 'foreach' or 'while'.


Quickly scanning down, these all look so long!

function rev($str) {
    return $str?rev(substr($str,1)).$str[0]:'';
}

Recursive so obviously doesn't work on strings longer than 100 chars.


Since this sounds like homework question I'll tell you how but you code it yourself. Turn the string into an array with a cast. Then use one of the array sorting functions that takes a user defined sorting function.


function reverseString($string) {
  return shell_exec(sprintf('ruby -e \'puts "%s".reverse\'', preg_replace("/\"/", "\\\"", $string)));
}


Recursive solution:

function sr( $txt ){
    return $txt[ strlen( $txt ) - 1 ] . ( ( strlen( $txt ) > 1 )?sr( substr( $txt, 0, strlen($txt)-1 ) ):null) ;
}

echo sr( "abc def ghi jklm" );

Explanation:

return $txt[ strlen( $txt ) - 1 ] // return last byte of string
.                                 // concatenate it with:
(( strlen( $txt ) > 1 ) ?         // if there are more bytes in string
 sr( substr( $txt, 0, strlen( $txt ) - 1 ) // then with reversed string without last letter
 : null );                        // otherwise with null

To make it work with zero-length string, another conditional expression was added:

return (strlen($txt))? ($txt[ strlen( $txt ) - 1 ] . ( ( strlen( $txt ) > 1 )?sr( substr( $txt, 0, strlen($txt)-1 ) ):null)):"" ;


    <?php
    // Reversed string and Number
    //  For Example :
        $str = "hello world. This is john duvey";
        $number = 123456789;
        $newStr = strrev($str);
        $newBum = strrev($number);

        echo $newStr;
        echo "<br />";
        echo $newBum;

OUTPUT : 
 first : yevud nhoj si sihT .dlrow olleh
 second: 987654321`enter code here`


Meets all your requirements but works only in PHP 5.3 or higher. Making it work on others is left as homework.

function reverse($str) {
        $i=0;
        $j=strlen($str)-1;
start:
        if($i>=$j) {
                goto done;
        }
        $tmp = $str[$j];
        $str[$j--] = $str[$i];
        $str[$i++] = $tmp;
        goto start;
done:
        return $str;
}   


function reverse_string($string) {
    if($string !== '')
        return substr($string, -1).reverse_string(substr($string, 0, strlen($string)-2));     
}


A recursive solution. Feels like something like that is what your teacher is looking for.

function my_strrev ($str) {
  $length = strlen($str);
  switch ($length) {
      case 0: return '';
      case 1: return $str; break;
      case 2: return $str[1] . $str[0];
      default :
          return $str[$length-1] .  my_strrev(substr($str,1,-1)) . $str[0];
          break;
  }
}

It swaps the first and the last letter and than makes the same with the rest of the string.

Update: Inspired by mateusza I created another solution (its fun ;))

function my_strrev2 ($str) {
  return $str
    ? my_strrev2(substr($str, 1)) . $str[0]
    : '';
}

It works similar to mateuszas, but this one appends the first character, instead of prepend the last one.


My answer is OOP and uses recursion. Takes care by itself of the recursion limit.

class StringReverser
{
    public $reversed_string;
    public function __construct ($string) {
        $original_recursion_limit = ini_get('pcre.recursion_limit');
        $array = str_split($string);
        krsort($array);
        $i = strlen($string);
        ini_set('pcre.recursion_limit', $i+1);
        $this->add2string($string, $i, $array);
        ini_set('pcre.recursion_limit', $original_recursion_limit);
    }

    public function reverse() {
        return $this->reversed_string;
    }

    private function add2string ($s, $i,  $a) {
        if($i) {
            $i--;
            $this->reversed_string .= $a[$i];
            $this->add2string($s, $i,$a, $this->reversed_string);
        }
    }
}


$string =  "Elzo Valugi";
echo $string ."<br>";
$reverser = new StringReverser($string);
echo $reverser->reverse();


<?php
 $string="jomon is name my";
 for($i=strlen($string);$i>=0;$i--)
 {
     $char.=$string{$i};    
 }
 echo $char."<br/>";

 for($i=0; $i<strlen($char);$i++)
 {
     if($char[$i+1]==" " || $char[$i+1]=="")
     {
         for($temp=$i; $temp>=0 && $char[$temp]!=' '; $temp--)
             echo $char[$temp];
     }
     echo " ";
 }    
 ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜