PHP String Exercises: Get the last three characters of a string
PHP String: Exercise-7 with Solution
Write a PHP script to get the last three characters of a string.
Sample String : '[email protected]'
Visual Presentation:
Sample Solution:
PHP Code:
<?php
$str1 = '[email protected]'; // Assigns an email address to the variable $str1
echo substr($str1, -3)."\n"; // Extracts the last 3 characters from $str1 and echoes them
?>
Output:
com
Explanation:
In the exercise above,
- Defines a string variable '$str1' containing the value '[email protected]'. This variable holds an email address.
- Uses the "substr()" function to extract the last 3 characters from the string stored in '$str1'. The "substr()" function takes two parameters: the string to extract from ($str1), and the starting position of the substring (-3, indicating the third character from the end of the string).
- Echoes the extracted substring to the output, followed by a newline character ("\n").
Flowchart:
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to extract the user name from the specified email ID.
Next: Write a PHP script to format values in currency style.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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/php-string-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics