w3resource

PHP Exercises: Create a new string using three copies of the last two character of a given string of length atleast two

PHP Basic Algorithm: Exercise-61 with Solution

Write a PHP program to create a new string using three copies of the last two character of a given string of length atleast two.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that repeats the last two characters of a string three times
function test($s1)
{
    // Use substr to extract the last two characters of s1
    $last2 = substr($s1, strlen($s1) - 2);
    
    // Concatenate the last2 string repeated three times
    return $last2 . $last2 . $last2;
}

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

Explanation:

  • Function Purpose:
    • The test function takes a string $s1 and returns a new string where the last two characters of $s1 are repeated three times.
  • Extracting Last Two Characters:
    • The function uses substr($s1, strlen($s1) - 2) to get the last two characters of $s1 and stores them in $last2.
  • Repeating and Concatenating:
    • It then creates a new string by concatenating $last2 three times ($last2 . $last2 . $last2), which repeats the last two characters three times.

Output:

lololo
HiHiHi

Flowchart:

Flowchart: Create a new string using three copies of the last two character of a given string of length atleast two.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to insert a given string into middle of the another given string of length 4.
Next: Write a PHP program to create a new string using first two characters of a given string. If the string length is less than 2 then return the original string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-61.php