Hi all, this is a handy tutorial in php to limit the number of characters. I recently did this for a project I’m working on, where I need to limit a post code form field to only show part of the post code, but this has other uses too, I do realise this is relatively simple, but hopefully this will help some of you out. Today we are going to use substr.
Usage:
substr($string, $start, $length);
It returns a portion of the string, by the start and length parameters.
<?php $makethisless = "Giant Shrimp"; echo "This is the long version of $makethisless <br />"; $nowshort = substr($makethisless, 0,5); echo "This is the short version only 5 characters : $nowshort"; ?>
Now you can see this isnt complicated, but it shows only 5 characters of it starting from value of 0.
Here are some more examples from the PHP.net website, your bible!
<?php
$rest = substr("abcdef", -1); // returns "f"
$rest = substr("abcdef",-2); // returns "ef"
$rest = substr("abcdef",-3,1); // returns "d"
?>
I think the hardest example is the last one, just to explain, it starts from ‘-3′, which if you count backwards, it goes to ‘d’. Then ‘1′ indicates the length, so its 1, so it shows only 1 letter, being ‘d’, ok? good.
Well thats about it, but you WILL need this at some point, so you can say you learned it here.
Cheers
Wuup Team
NOTE: Copying and pasting this out copies the wrong type of ” (quotation marks) so please download the source, I have renamed the extention to a .txt file.
Click on the link below:







Mike on 18 February, 2009
I really liked you tutorial here. It really helps to see someone else showing people how to use the php code. It’s such a great tool. I have used curl to get html source code from a website then some substring functions to find a certain phrase in the code and then use the function above to use the information I got to cut out just the part I want to keep.
Alan Hamlyn on 18 February, 2009
no probs, happy to help