w3resource

PHP Exercises: Move the last two characters to the start of a given string of length at least two


68. Move Last Two Characters to Start

Write a PHP program to move the last two characters to the start of a given string of length at least two.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that rearranges the last two characters of a string with the rest of the string
function test($s1)
{ 
    // Use substr to extract substrings and rearrange them
    return substr($s1, strlen($s1) - 2, 2) . substr($s1, 0, strlen($s1) - 2);
}

// Test the 'test' function with different strings and display the results
echo test("Hello")."\n";
echo test("JS")."\n";
?>

Explanation:

  • Function Definition:
    • A function named test is defined, which takes one parameter, $s1, representing the input string.
  • Character Rearrangement:
    • Inside the function, two substr calls are used to rearrange the characters of the input string $s1:
      • substr($s1, strlen($s1) - 2, 2) extracts the last two characters of the string.
      • substr($s1, 0, strlen($s1) - 2) extracts all characters of the string except for the last two.
  • Concatenation:
    • The function returns the concatenation of the last two characters (extracted first) followed by the rest of the string (extracted second), effectively moving the last two characters to the front of the string.

Output:

loHel
JS

Flowchart:

Flowchart: Move the last two characters to the start of a given string of length at least two.

For more Practice: Solve these Related Problems:

  • Write a PHP script to take the last two characters of a string and place them at the beginning, preserving the order.
  • Write a PHP function to extract the ending two letters and prepend them to the remaining substring.
  • Write a PHP program to perform a string rotation that shifts the final two characters to the start.
  • Write a PHP script to create a new string by concatenating the last two characters before the initial segment.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Write a PHP program to move the first two characters to the end of a given string of length at least two.
Next: Write a PHP program to create a new string without the first and last character of a given string of any length.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.