Strip Off Characters from String Using PHP (substr)
First, if you only want to pull on character from a string, it’s a lot easier to use the following:
$str = 'puppy'; echo $str; // p echo $str; // u echo $str; // p ...and so on
Here’s the basic concept behind substr:
substr($string, start [,length]) – length is in brackets because it’s optional
Now let’s use this function to get a better idea of what it does.
$str = 'categories'; echo substr($str,0); // 'categories' because we asked to start at the first character (which is 0 from the first example above) and goes right until end of str echo substr($str,3); // 'egories' because started at the third character in the str and went to the end echo substr($str,-1); // 's' this is different from above because it starts at the end and goes left that number of characters echo substr($str,-3); // 'ies' echo substr($str,0,-1); // 'categorie' strips last letter off echo substr($str,3,4); // 'egor' - starts at the fourth character (remember 0 is the first) and shows 4 characters total (length) echo substr($str,1,3); // 'ate' - starts at the second character and shows 3 characters total (length) echo substr($str,1,-2); // 'ategori' because we started at the second character and also stripped off the last two with the "-2" echo substr($str,-3,-2); // 'i' since we're starting from the third character from the left and then are stripping off two characters from that with the "-2"
A practical use that I use quite often is if I only want to display a preview description rather than showing the whole large description.
$str = 'Great for home, school or travel. Wonderful gift item!'; echo substr($str,0,30).'...'; // displays "Great for home, school or trav..." // quick change to prevent any word from being cut off // strrpos finds the last occurrence of a substring in a string echo substr($str,0,strrpos(substr($str,0,30),' ')).'...'; // Great for home, school or...
There are other very practical reasons to use . Please leave a comment if you have one of your own that you think would be beneficial to share.