PHP Exercises: Create a new string using the first and last n characters from a given string of length at least n
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.
- 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.
Concatenation of Substrings:
Output:
Ho Pyon on oo
Flowchart:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics