Reverse string with php

How to reverse a string and replace chars?

In prose that is: First turn the string into an array of words Second, inverse the order of the elements in that array Reading the whole list of string and array functions in PHP is VERY helpful and will save tons of time. Solution 2: You can play around with tis one, not tested a lot though Solution 3: I think you can try with: I have a second version in order to works with strings: Solution 4: I kept it short: The behavior of cases like is it returns , which I thought was more likely intended if you’re specifying an array.

How to reverse a string and replace chars?

I have been asked by an interviewer for a test:

$string = "This is sample string"; // Output: "string_sample_is_This"; 

what does this question mean.

I assumed that he was asking about a simple echo , am I right or would he expected something else from me ?

He definetly asked for something else .

That looks more like you are being asked to reverse the order of the tokens in the string and replace the delimiter from single spaces to the _ character. I would assume that or something similar to such was being asked.

Читайте также:  Php mysql переменные в строке

No he told to reverse the sentence and echo the string.

Reverse A String in PHP || PHP program to reverse a string, https://tinyurl.com/yr9nhjmy reverse a string in php , php program to reverse a string , php program to reverse a string from input,arches related to php program

Reverse A String in PHP || PHP program to reverse a string

https://tinyurl.com/yr9nhjmy reverse a string in php , php program to reverse a string , php program to reverse a string from input,arches related to php program

Reverse the order of space-separated words in a string

What would be the best way to reverse the order of space-separated words in a string?

Hello everybody in stackoverflow 
stackoverflow in everybody Hello 
$s = 'Hello everybody in stackoverflow'; echo implode(' ', array_reverse(explode(' ', $s))); 
$reversed_string = implode(' ', array_reverse($words)); 

Reading the whole list of string and array functions in PHP is VERY helpful and will save tons of time.

The above answer, strrev reverses the entire string. To reverse the order of the words:

$str = 'Hello everybody in stackoverflow'; $tmp = explode(' ', $str); $tmp = array_reverse($tmp); $reversed_str = join(' ', $tmp); 
$tmp = explode(' ', $string); array_reverse($tmp); $string = implode(' ', $tmp); 

Str_repeat reverse (shrink strings)

str_repeat(A, B) repeat string A , B times:

$string = "This is a " . str_repeat("test", 2) . "! " . str_repeat("hello", 3) . " and Bye!"; // Return "This is a testtest! hellohellohello and Bye!" 
str_shrink($string, array("hello", "test")); // Return "This is a test(x2)! hello(x3) and Bye!" or // "This is a [test]x2! [hello]x3 and Bye!" 

Best and efficient way for create str_shrink function?

Here are two versions that I could come up with.

The first uses a regular expression and replaces duplicate matches of the $needle string with a single $needle string. This is the most vigorously tested version and handles all possibilities of inputs successfully (as far as I know).

function str_shrink( $str, $needle) < if( is_array( $needle)) < foreach( $needle as $n) < $str = str_shrink( $str, $n); >return $str; > $regex = '/(' . $needle . ')(?:' . $needle . ')+/i'; return preg_replace_callback( $regex, function( $matches) < return $matches[1] . '(x' . substr_count( $matches[0], $matches[1]) . ')'; >, $str); > 

The second uses string manipulation to continually replace occurrences of the $needle concatenated with itself. Note that this one will fail if $needle.$needle occurs more than once in the input string (The first one does not have this problem).

function str_shrink2( $str, $needle) < if( is_array( $needle)) < foreach( $needle as $n) < $str = str_shrink2( $str, $n); >return $str; > $count = 1; $previous = -1; while( ($i = strpos( $str, $needle.$needle)) > 0) < $str = str_replace( $needle.$needle, $needle, $str); $count++; $previous = $i; >if( $count > 1) < $str = substr( $str, 0, $previous) . $needle .'(x' . $count . ')' . substr( $str, $previous + strlen( $needle)); >return $str; > 

Edit: I didn’t realize that the desired output wanted to include the number of repetitions. I’ve modified my examples accordingly.

You can play around with tis one, not tested a lot though

function shrink($s, $parts, $mask = "%s(x%d)") < foreach($parts as $part)< $removed = 0; $regex = "/($part)+/"; preg_match_all($regex, $s, $matches, PREG_OFFSET_CAPTURE); if(!$matches) continue; foreach($matches[0] as $m)< $offset = $m[1] - $removed; $nb = substr_count($m[0], $part); $counter = sprintf($mask, $part, $nb); $s = substr($s, 0, $offset) . $counter . substr($s, $offset + strlen($m[0])); $removed += strlen($m[0]) - strlen($part); >> return $s; > 
 return preg_replace($pattern, '$', strtr($string,$tr)); > echo $string; echo '
'; echo str_shrink($string,array('test','hello')); //This is a test(x2)! hello(x3) and Bye! ?>

I have a second version in order to works with strings:

 return preg_replace($pattern, '$', strtr($string,$tr)); > echo $string; echo '
'; echo str_shrink($string,array('test','hello')); //This is a test(x2)! hello(x3) and Bye! echo '
'; echo str_shrink($string,'test'); //This is a test(x2)! hellohellohello and Bye! ?>
function str_shrink($haystack, $needles, $match_case = true) < if (!is_array($needles)) $needles = array($needles); foreach ($needles as $k =>$v) $needles[$k] = preg_quote($v, '/'); $regexp = '/(' . implode('|', $needles) . ')+/' . ($match_case ? '' : 'i'); return preg_replace_callback($regexp, function($matches) < return $matches[1] . '(x' . (strlen($matches[0]) / strlen($matches[1])) . ')'; >, $haystack); > 

The behavior of cases like str_shrink(«aaa», array(«a», «a(x3)»)) is it returns «a(x3)» , which I thought was more likely intended if you’re specifying an array. For the other behavior, giving a result of «a(x3)(x1)» , call the function with each needle individually.

If you don’t want multiples of one to get «(x1)» change:

 return $matches[1] . '(x' . (strlen($matches[0]) / strlen($matches[1])) . ')'; 
 $multiple = strlen($matches[0]) / strlen($matches[1]); return $matches[1] . (($multiple > 1) ? '(x' . $multiple . ')' : ''); 

String — strpos function in reverse in php, Not to discourage you too much from asking, but always remember to Google first — when searching for strpos function in reverse in php, strrpos() turns up in third …

Источник

Reverse String in PHP

reverse string in php

In this article, we will learn about Reverse String in PHP. A string is the collection of characters that are called from the backside. These collections of characters can be used to reverse either the PHP function strrev() or by using the simple PHP programming code. For example on reversing PAVANKUMAR will become RAMUKNAVAP

Web development, programming languages, Software testing & others

  • At first, assigning the string to the variable.
  • Now calculate the string length.
  • Now create a new variable in order to store the reversed string.
  • Then Proceed with the loop like for loop, while loop and do while loop etc..
  • Concatenating the string inside of the loop.
  • Then display/print the reversed string which is stored in the new variable which is created in the middle.

Reverse String in PHP Using Various Loops

Various Loops like FOR LOOP, WHILE LOOP, DO WHILE LOOP, RECURSIVE METHOD, etc.. in order to Reverse the String in the PHP Programming Language.

1. Using strrev() function

  • The below example/syntax will reverse the original string using already predefined function strrev() in order to reverse the string. In the example, a $string1 variable is created in order to store the string I mean the original string then the echo statement is used in order to print the original string and the reversed string with the help of strtev() function and then print by concatenating both.
  • You can check the output of the program below to check whether the string is reversed or not.

Reverse String in PHP - 1

2. Using For Loop

  • In the below example, the “$string1” variable is created by assigning the string1 variable’s value as “PAVANSAKE”. Then the $length variable is created in order to store the length of the $string1 variable using the strlen() function. Now the for loop is used with initialization, condition and incrementation values as “$length1-1”, “$i1>=0”, “$i1 – -”. Then the $string1 variable’s index values are calling from the backside using the initialization of $i1 equals to $length-1.
  • At first, FOR LOOP will start with the value of the length of the “original string – 1” value. Then the loop starts running by checking the condition “i1>=0” then the original string’s index is called backward likewise loop will print each index value from the back for each iteration until the condition is FALSE. At last, we will get the Reverse of the string using FOR loop.

Reverse String in PHP - 2

3. Using While Loop

  • Here in the below example while loops used in order to print the string which is reversed using the original string “PAVANSAKEkumar”.
  • In the below syntax/php program, at first, a $string1 variable is assigned with string value “PAVANSAKEkumar” then we calculate the length of the $string1 variable’s value and stored in the $length1 variable. It will be an integer always. Now the $i1 variable is the length of the string variable’s value -1($length1-1).
  • Now we start with the WHILE loop here using the condition “$i1>=0” then after that we will print the string’s index value from the back because the $i1 value is the last of the index value of the original string. After this, decrementing will be done in order to reverse the original string($i1=$i1-1).

Reverse String in PHP - 3

4. Using do while Loop

  • The program of reversing the string in PHP using the DO while loop is listed below. In the below example just like the WHILE LOOP. Every Logic term is the same as the WHILE LOOP but does follow is a bit different it will print the output first rather than checking the condition at first.
  • So even though if you print an output even if the condition result is FALSE.

Reverse String in PHP - 4

5. Using the Recursion Technique and the substr()

  • Here in the below example reversing the string is done using the recursion technique and the substr() function. Substr() function will help in getting the original string’s substring. Here a new function called Reverse() also defined which is passed as an argument with the string.
  • At each and every recursive call, substr() method is used in order to extract the argument’s string of the first character and it is called as Reverse () function again just bypassing the argument’s remaining part and then the first character concatenated at the string’s end from the current call. Check the below to know more.
  • The reverse () function is created to reverse a string using some code in it with the recursion technique. $len1 is created to store the length of the string specified. Then if the length of the variable equals to 1 i.e. one letter then it will return the same.
  • If the string is not one letter then the else condition works by calling the letters from behind one by one using “length – -“ and also calling the function back in order to make a recursive loop using the function (calling the function in function using the library function of PHP). $str1 variable is storing the original string as a variable. Now printing the function result which is the reverse of the string.
 else < $len1--; return Reverse(substr($str1,1, $len1)) . substr($str1, 0, 1); >> $str1 = "PavanKumarSake"; print_r(Reverse($str1)); ?>

recursion technique and the substr()

6. Reversing String without using any library functions of PHP

  • The below syntax/ program example is done by swapping the index’s characters using the for loop like first character’s index is replaced by the last character’s index then the second character is replaced by the second from the last and so on until we reach the middle index of the string.
  • The below example is done without using any of the library functions. Here in the below example, $i2 variable is assigned with the length of the original string-1 and $j2 value is stored with value as “0” then in the loop will continue by swapping the indexes by checking the condition “$j2
 return $str2; > $str2 = "PAVANKUMARSAKE"; print_r(Reverse($str2)); ?>

library functions of PHP

Conclusion

I hope you understood the concept of logic of reversing the input string and how to reverse a string using various techniques using an example for each one with an explanation.

This is a guide to Reverse String in PHP. Here we discuss the logic of reversing the input string and how to reverse a string using various loops with respective examples. You can also go through our other related articles to learn more –

25+ Hours of HD Videos
5 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

92+ Hours of HD Videos
22 Courses
2 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

83+ Hours of HD Videos
16 Courses
1 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

PHP Course Bundle — 8 Courses in 1 | 3 Mock Tests
43+ Hours of HD Videos
8 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Оцените статью