linein designs

15 Feb, 2008

UPDATED: Strip Off Characters from String Using PHP (substr)

Posted by: john In: php| programing

substr_icon.jpgAlmost 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,0,-1); // 'categorie' strips last letter off
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,0,25).'...'; // displays "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.

Similar Posts:

11 Comments »

Comment by Sam

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.

Comment by john

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.

 
 
Comment by Alan Williams

Hi
I am trying to get the following to not display the last 3 characters which are a decimall point an 2 zeros. However as it is in the middle of HTML whatever I try seems not to work. The full code is below and the excerpt (I have isolated it in the bulk code below for ease) I want to shorten is this: $al[SquareMeters] Square Metres – any suggestions?

$ShowInfo = “\n\t\n\tLocation: $a1[country]\n\tPrice: $aset[Currencya]$MyPriceClick any image to enlarge\n\n\n\n\tProperty ID: $a1[ListingID]Property Overview:$a1[rooms] Bedroom(s)$a1[bathrooms] Bathroom(s)$a1[garage] Car GarageBuild Size:

$al[SquareMeters] Square Metres

Plot Size: $a1[LotSize] Square MetresAge of Property: $a1[HomeAge] yearsDetailed Description$descMore Details:“;

Comment by john

If you’re just trying to drop off the decimal points, then you should use ceil() (http://us3.php.net/ceil).

Otherwise you could use, substr($all[SquareMeters],0,-3); to drop off the decimal and the two numbers after it. But again ceil() would be better in case your number ever had three decimal places.

 
 
Comment by Roger Coathup

I have a series of strings, e.g.

Living: news
Beauty: news
Fashions: features

and want to strip off all the text up to and including the ‘:’.

Is there any easy way to do this?

Comment by john

Yes, there is an easy way to do this. You’ll want to use explode() to split apart the text where the : is.

$text = ‘Living: news’;
$text_bits = explode(‘:’,$text);

now you have an array that looks like this
array(0 => ‘Living’, 1 => ‘news’);

Then to display it:
echo $text_bits[1]; // would display just “news”

Basically what you’re doing is spiting the text at the : into two parts and then echoing the part you want.

 
 
Comment by John

Great tutorial. Worked perfect first time. Thank you for making it simple!

 
Comment by amscray

Thanks a lot for writing this article. I found it to be a very useful reference.

 
Comment by RedMatrix

Thanks for the easy code. I was wondering how to do it to read a file that has headings that start with a colon, and then use the heading in an <h2>, but everything else in a <li>.

I am building a list of products for an ebay script, but wanted it to be in categories to make it easier on the visitor. RE site: BuyWiiFitPlus.com

Comment by john

I’m not 100% sure what you’re looking for so please use the contact form [http://www.linein.org/blog/contact/] and shoot me a message with a little more information on what you’re trying to do.

Comment by RedMatrix

No, I didn’t have a question. I tried to mean than you answered my question. Thanks.

(Comments wont nest below this level)
 
 
 
Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.

Trackback responses to this post



Please Support Our Sponsors

A Payday advance can be a great way to get back on track.

Banner

About

My name is John Veldboom and have been in design and web programing for just over 8 years now. Started off as a hobby in high school but it has developed into a full time job now. I always tell people that if I wasn't doing this at work each day, I would be at home doing it for free. I love it!

Please visit the contact page to drop me a message.