PHP Exercises: Move the first two characters to the end of a given string of length at least two
PHP Basic Algorithm: Exercise-67 with Solution
Write a PHP program to move the first two characters to the end of a given string of length at least two.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that rearranges the characters of a string
function test($s1)
{
// Use substr to extract substrings and rearrange them
return substr($s1, 2, strlen($s1) - 2) . substr($s1, 0, 2);
}
// Test the 'test' function with different strings and display the results
echo test("Hello")."\n";
echo test("JS");
?>
Explanation:
- Function Definition:
- The function test is defined to take one string parameter, $s1.
- Character Rearrangement:
- Inside the function, two substr calls are used to rearrange the characters of the input string $s1:
- substr($s1, 2, strlen($s1) - 2) extracts a substring starting from the third character to the end of the string.
- substr($s1, 0, 2) extracts the first two characters of the string.
- Concatenation:
- The function returns the concatenation of the two extracted substrings, effectively moving the first two characters to the end of the string.
Output:
lloHe JS
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to concat two given string of length atleast 1, after removing their first character.
Next: Write a PHP program to move the last two characters to the start of a given string of length at least two.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-67.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics