w3resource

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


72. Concat First and Last n Characters

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";
?>

Explanation:

  • Function Definition:
    • A function named test is defined, which takes two parameters:
      • $s1: the input string.
      • $n: the number of characters to extract from the start and end of the string.

    Concatenation of Substrings:

    • The function uses substr to concatenate parts of the string:
      • substr($s1, 0, $n) extracts the first n characters of $s1.
      • substr($s1, strlen($s1) - $n, $n) extracts the last n characters.
    • The two substrings are concatenated and returned as a single string.

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.

For more Practice: Solve these Related Problems:

  • Write a PHP script to output a new string formed by concatenating the first n and last n characters of the input string.
  • Write a PHP function to extract the beginning and ending segments of a string as determined by an integer n and join them together.
  • Write a PHP program to slice an input string into two parts based on the parameter n and concatenate the parts.
  • Write a PHP script to check string length and then create a new string from its first and last n letters.

Go to:


PREV : Check if String Ends with "on".
NEXT : Substring of Length 2 at Given Index.

PHP Code Editor:



Contribute your code and comments through Disqus.

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.