Posted by john in php, programing
Almost a year ago I wrote a quick article on how you can strip off characters using PHP’s built in function substr. But after reading it again, even I was not clear how it worked so how would it ever help anyone.
First, if you only want to pull on character from a string, it’s a lot easier to use the following:
$string = 'puppy'; echo $string[0]; // p echo $string[1]; // u echo $string[2]; // 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.
$string = ‘categories’;
echo substr($string, 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 string
echo substr($string, 3); // ‘egories’ because started at the third character in the string and went to the end
echo substr($string, -1); // ’s’ this is different from above because it starts at the end and goes left that number of characters
echo substr($string, -3); // ‘ies’
echo substr($string,3,4); // ‘egor’ - starts at the fourth character (remember 0 is the first) and shows 4 characters total (length)
echo substr($string,1,3); // ‘ate’ - starts at the second character and shows 3 characters total (length)
echo substr($string,1,-2); // ‘ategori’ because we started at the second character and also stripped off the last two with the “-2″
echo substr($string,-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.
$text = ‘Great for home, school or travel. Wonderful gift item!’;
echo substr($text, 25).’…’; // displays “Great for home, school or…”
There are other very practical reasons to use substr. Please leave a comment if you have one of your own that you think would be beneficial to share.







July 5th, 2008 at 10:13 am
What if you want to exclude only some content.
Example Text: Children Of Men (R)
Goal: Remove only the (R)
Yes, you could use substr and set to only show the first 13 characters, but what if the example text is something like The Man In the Mirror Is Looking (R) and you want to keep only “The Man In The Mirror Is Looking” in this case you wouldn’t be able to use the same substr for the first 13 characters.
[Reply]
john reply on July 6th, 2008:
In that case you would want to use
str_replace.For example:
$text = ‘Children Of Men (R)’;
$goal = str_replace(’(R)’,”,$text);
This will replace the ‘(R)’ with nothing (”).
Just let me know if you have any questions about this.
[Reply]