w3resource

PHP Exercises: Concat two given string of length atleast 1, after removing their first character


66. Remove First Character from Both and Concat

Write a PHP program to concat two given string of length atleast 1, after removing their first character.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that concatenates substrings excluding the first character
function test($s1, $s2)
{ 
    // Use substr to extract substrings excluding the first character and concatenate them
    return substr($s1, 1, strlen($s1) - 1) . substr($s2, 1, strlen($s2) - 1);
}

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

Explanation:

  • Function Definition:
    • The function test is defined to take two string parameters, $s1 and $s2.
  • Substring Extraction:
    • Inside the function, substr is used to extract substrings from both $s1 and $s2, excluding their first characters:
      • substr($s1, 1, strlen($s1) - 1) extracts all characters from $s1 starting from the second character.
      • substr($s2, 1, strlen($s2) - 1) does the same for $s2.
  • Concatenation:
    • The function returns the concatenated result of these substrings from $s1 and $s2.

Output:

elloi
Sython

Flowchart:

Flowchart: Concat two given string of length atleast 1, after removing their first character.

For more Practice: Solve these Related Problems:

  • Write a PHP script to remove the first character from each of two strings and then concatenate the remaining parts.
  • Write a PHP function to trim the leading character of two inputs and merge them into a single string.
  • Write a PHP program to process two strings, cut off the first character, and join them into one resultant string.
  • Write a PHP script to implement a substring extraction from both strings starting at index 1 before concatenation.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new string from two given string one is shorter and another is longer. The format of the new string will be long string + short string + long string.
Next: Write a PHP program to move the first two characters to the end of a given string of length at least two.

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.