View Full Version : Simple Question: Trimming Strings (not ltrim or rtrim or trim)

03-01-2007, 02:10 AM
G'day guys,

Wondering if you could help me out with this (no doubt easy one):

What I want to do is trim a string by x number of characters either from the left or right as desired:


For the string:

$string = "2007-01-05 12:20:00";

I want to remove the last ' 12:20:00' bit which is 9 characters long.
now the way I have managed this so far is to explode the string into an array, then echoing the first part of the array:

$string = "2007-01-05 12:20:00";
$string = explode(" ", $string);
echo $string[0];

But now as I want to also remove the year '2007-' which is the frist 5 characters of the string - now an array - I figure instead of doing another explode by '-' and calling the [1] and [2] part of the array surely I can just trim off x amount of characters.... I could with ASP.... Please enlighten me. I looked at the trims (l,r,) but they only remove whitespace and a chosen character... or am I wrong....

Thanks in advance!

03-01-2007, 02:41 AM
Do it all at once with a single statement - http://www.php.net/manual/en/function.substr.php

03-01-2007, 03:37 PM
In your case, you'd use it like this:

$string = "2007-01-05 12:20:00";
$date = substr($string, 5, 5); // string starts at 0, since you want character 6 you get 6 - 1= 5, and you want the 01-05 which is 5 characters long

03-02-2007, 06:30 AM
Great! Brilliant thanks.... the learning never stops :)