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

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.

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.



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