PHP Exercises: Create a new string using first two characters of a given string
62. First Two Characters Extraction
Write a PHP program to create a new string using first two characters of a given string. If the string length is less than 2 then return the original string.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that extracts the first two characters of a string
function test($s1)
{
// Check if the length of s1 is less than 2
if (strlen($s1) < 2) { // If true, return s1 as is return $s1; } else { // If false, use substr to extract the first two characters of s1 return substr($s1, 0, 2); } } // Test the 'test' function with different input strings and display the results echo test("Hello")."\n"; echo test("Hi")."\n"; echo test("H")."\n"; echo test(" ")."\n"; ?>
Explanation:
- Function Definition:
- The function test is defined to take one parameter, $s1, which is expected to be a string.
- Length Check:
- The function first checks if the length of $s1 is less than 2 using strlen($s1) < 2.
- Return Logic:
- If Length < 2:
- If the length is less than 2, it returns $s1 as is (meaning the entire string, whether it's empty or a single character).
- If Length ≥ 2:
- If the length is 2 or more, it uses substr($s1, 0, 2) to extract the first two characters of the string and returns them.
Output:
He Hi H
Flowchart:
Flowchart: Create a new string using first two characters of a given string.For more Practice: Solve these Related Problems:
- Write a PHP script to output a new string using the first two characters of the input, reverting to the original if its length is below two.
- Write a PHP function to conditionally extract the initial two letters from a string, handling short strings appropriately.
- Write a PHP program to slice the first two characters, using a fallback to return the whole string if necessary.
- Write a PHP script to check the length of a string and then either output the first two characters or the string itself.
Go to:
PREV : Three Copies of Last Two Characters.
NEXT : First Half of Even-Length String.
PHP Code Editor:
Contribute your code and comments through Disqus.