w3resource

PHP String Exercises: Get the last three characters of a string


7. Get Last Three Characters

Write a PHP script to get the last three characters of a string.

Sample String : '[email protected]'

Visual Presentation:

PHP String Exercises: Get the last three characters of a string

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:

Flowchart: Get the last three characters of a string

For more Practice: Solve these Related Problems:

  • Write a PHP script to retrieve the last three characters of a string using substr() and output them.
  • Write a PHP function that returns the last n characters of a given string and test it with different values of n.
  • Write a PHP program to extract the file extension from an email address by getting its last three characters, if applicable.
  • Write a PHP script to handle Unicode strings and correctly extract the last three multibyte characters.

Go to:


PREV : Extract Username from Email.
NEXT : Format as Currency.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.