w3resource

PHP Exercises: Create a new string using the first and last n characters from a given string of length at least n

PHP Basic Algorithm: Exercise-72 with Solution

Write a PHP program to create a new string using the first and last n characters from a given string of length at least n.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that concatenates the first 'n' characters and the last 'n' characters of the input string
function test($s1, $n)
{ 
   // Use substr to extract the first 'n' characters and concatenate with the last 'n' characters of the input string
   return substr($s1, 0, $n) . substr($s1, strlen($s1) - $n, $n);
}

// Test the 'test' function with different strings and 'n' values, then display the results using echo
echo test("Hello", 1)."\n";
echo test("Python", 2)."\n";
echo test("on", 1)."\n";
echo test("o", 1)."\n";
?>

Sample Output:

Ho
Pyon
on
oo

Flowchart:

Flowchart: Create a new string using the first and last n characters from a given string of length at least n.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check if a given string ends with "on".
Next: Write a PHP program to create a new string of length 2 starting at the given index of a given string.

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.