RSS Feed Icon The WebDevil - Jeremy Lindblom

WebDevilAZ

The Portfolio & Blog
of Jeremy Lindblom

PHP Tidbits: trim magic

February 26, 2009 at 8:00 pm

It turns out that the trim() functions of PHP are even more useful than I originally thought. The trim functions ( trim(), ltrim() and rtrim() ) are normally used to trim whitespace from the ends of strings. However, the definition of trim from the PHP Manual states: “Strip whitespace (or other characters) from the beginning and end of a string”. I added emphasis (literally) to the part that says “(or other characters)”. That means we can trim anything from a string. I hope you can see the value of this. Well, I’ll show you a brief example anyway after the fold.

A common problem where this could be helpful is in string building. Let’s say you are building a list of items that you want to be associated with an index as a part of the item’s name, and you want to separate them with a comma and a space. Here’s the example:

1
2
3
4
5
6
<?php
  $list = '';
  for ($i = 0; $i < 10; $i++)
      $list .= 'item' . $i . ', ';
  echo $list;
?>

The output for this code will be “item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, ”. Note the trailing comma and space. How have people fixed this problem in the past? Well, you can change the for loop a bit and add the last item outside of the for loop or add some kind of conditional statement. You can also use a combination of things like strpos() or strrpos() and substr(). There is an easier solution using rtrim(). Look at this example:

1
2
3
4
5
6
<?php
  $list = '';
  for ($i = 0; $i < 10; $i++)
      $list .= 'item' . $i . ', ';
  echo rtrim($list, ', ');
?>

In line 5 we’ve changed the code to be $list = rtrim($list, ', '); which utilizes the trimming of “other characters”. Pretty nifty, eh? In some cases you may also opt for a solution using an array. The implode() and explode() functions are some of the most useful functions I know. Let’s solve the same problem with implode():

1
2
3
4
5
6
<?php
  $list = array();
  for ($i = 0; $i < 10; $i++)
      $list[] = 'item' . $i;
  echo implode(', ', $list);
?>

Alright, that’s your PHP tidbit for today. Mmm…

Share This Post:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • TwitThis
  • Reddit
  • MySpace
  • LinkedIn
  • Mixx
  • Design Float
  • Slashdot
  • Yahoo! Buzz
  • Sphinn
  • Technorati
  • Google Bookmarks
Category: Programming Tidbits, Web Development
Tags:


Comments






Clicky Web Analytics

©2008-2009 Jeremy Cole Lindblom. All rights reserved. Design and development by Jeremy Lindblom.

WebDevilAZ is proudly powered by Wordpress and Panels960. Subscribe to my RSS feed.