There are many post you may find reversing a string by each characters, but in this post we are going to see how to write a PHP program to reverse the entire sentence word by word (order of the word) by a given N words at a time.
Example 1:
Input: This is a short sentence
N: 1
Result: sentence short a is This
Example 2:
Input: This is a short sentence
N: 2
Result: sentence a short This is
Lets see the PHP code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<html> <head> <title>PHP code to reverse the order of a string word by word - Tutorialsmade.com</title> </head> <body> <h2>PHP code to reverse the order of a string word by word - Tutorialsmade.com</h2> <form action="" method="post"> Input Text: <input type="text" name="string"> Input N: <input type="number" min="1" max="10" name="n" value="1"> <button type="submit" name="submit">Submit</button> </form> </body> </html> <?php if(isset($_POST['submit'])){ $string = $_POST['string']; $n = $_POST['n']; print "<b>Input:</b> ".$string."<br>"; print "<b>N:</b>".$n."<br>"; print "<b>Result: </b>".special_reverse($string, $n); } function special_reverse($string, $n){ //explode the string by space $str_arr = explode(' ', $string); //get the n value $num = 1; $input_num = $n; $i = 0; $new_str = ''; foreach($str_arr as $str){ $new_str = $new_str.' '.$str; //$new_arr will keep the separated $new_arr[$i] = $new_str; //if the $input_num is less than $num. reset $num to 1 (else cond.) if($input_num > $num){ $num++; }else{ $i++; $num = 1; $new_str=''; } } //krsort to reverse the order of $new_arr krsort($new_arr); //now just implode the $new_arr again to form a sentence $final_str = implode(' ', $new_arr); return $final_str; } |
Read comments in the above script to understand how it works.
You can see the demo from the below link: