Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I store last 4 characters of a string in a variable?

Status
Not open for further replies.

jewel464g

Technical User
Jul 18, 2001
198
US
I need to get the last four characters of a string and store them in a variable called tax.

the string contains "Dublin0.07"
I want to store the last four characters in a variable named $tax so that $tax = 0.07 I am assuming that the decimal is considered a character.

I found this and it works but I'm sure there is a better way.
$str = "Dubline0.07";
$four = $str{strlen($str)-1};
$three = $str{strlen($str)-2};
$two = $str{strlen($str)-3};
$one = $str{strlen($str)-4};

$tax = "$one" . "$two" . "$three" . "$four";

When faced with a decision, always ask, 'Which would be the most fun?'
 
Use substr with a negative start
Code:
$rest = substr("abcdef", -4);    // sets $rest to "cdef"
$rest = substr("abcdef", -4, 2); // sets $rest to "cd"
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top