Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PHP code to reverse the order of words in a string by N words at a time.

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:


PHP code to reverse the order of a string word by word - Tutorialsmade.com

PHP code to reverse the order of a string word by word - Tutorialsmade.com

Input Text: Input N:
Input: ".$string."
"; print "N:".$n."
"; print "Result: ".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:

The post PHP code to reverse the order of words in a string by N words at a time. appeared first on TutorialsMade.



This post first appeared on TutorialsMade - Ultimate Tutorial, please read the originial post: here

Share the post

PHP code to reverse the order of words in a string by N words at a time.

×

Subscribe to Tutorialsmade - Ultimate Tutorial

Get updates delivered right to your inbox!

Thank you for your subscription

×