w3resource

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:

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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/php-exercises/php-string-exercise-7.php