ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

How to reverse a string without using any php function..

user-image
تم إضافة السؤال من قبل Alok Kumar singh Rinku , Software Developer , www.rensoftglobal.com
تاريخ النشر: 2013/09/18
Nouphal Muhammed
من قبل Nouphal Muhammed , Senior Web Developer , Planet Green Solutions

If your question is to reverse a string with out using any built in function in PHP,  then i have created a class that would reverse the string for you. If your need is to reverse a string with out using PHP, then javascript is the answer. First i will provide with the PHP class.

 

 class Reverse_String{    

        private $i;    

        private $str;    

        private $output;     

        public function __construct($str){     

                 $this->str = $str;    

        }     

       private function getStringLength(){       

                   for($i=0;;$i++){      

                           if(!$this->str[$i]){          

                                  $this->i = $i-1;            

                                  throw new Exception('My Error.Just wanted to get the string length.');       

                            }           

                  }        

       }    

       public function reverseString(){            

           try{            

                $this->getStringLength();        

           } catch (Exception $e) {            

                       for($j=$this->i;$j>=0;$j--){                            

                              $this->output .= $this->str[$j];          

                        }            

                        return $this->output;        

          }        

       }

}

 

$rev = new Reverse_String('String to be reversed');

$str = $rev->reverseString();

echo $str;

 

Here we are looping the string with an infinite loop in getStringLength() function, and we create a custom exception. In reverseString() function we catch that exception. Now we have the string length. Now simply a reverse looping will do our job.  Hope my answer is suited to your question.

If  you need a javascript alternative, then i have answered it. please go to this link :

http://www.bayt.com/en/specialties/q/26811/26811/

 

Julfkar  Moh Umar
من قبل Julfkar Moh Umar , Sr. Software Engineer , Aakash Edutech Private Limited

use simple mechanism as ::

$length=str_len($str);

 

for($i=$length -1;$i >=0;$i--)

{echo $str{$i};}

المزيد من الأسئلة المماثلة