Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Shortening a word with PHP

Hi everyone. I have a wordpress site that pulls meta data from a custom post type and displays it in two different spots on the site. The data is a date.. e.g. August 6 -- anyway I'd like to display the date in one spot on the site as Aug 6 and on the other spot as the full word August 6. Can anybody help me with this? I'm not a PHP expert... know it's possible just don't know how to do it.

3 Answers

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

There are (of course) a few different ways to do this. How is the started in the database?

  • Is it an actual date, in a format like this: 1375765200?
  • Or is it just a string, like this: "August 6"?

It's better for lots of reasons to store it as an actual date (option 1), and it's a little more logical how to shorten it. But if it's just a string (option 2), I'd probably write a series of string replacements.

$date = str_replace("January","Jan", $date);
$date = str_replace("February","Feb", $date);
...
$date = str_replace("December","Dec", $date);

Then I'd probably wrap all that in a function and place it in the functions.php file:

function shorten_month_name ($date) {
    $date = str_replace("January","Jan", $date);
    $date = str_replace("February","Feb", $date);
    ...
    $date = str_replace("December","Dec", $date);
    return $date;
}

Then in your theme, you can replace this ---

echo "August 6";

-- with this --

echo shorten_month_name("August 6");

Does that help?

Thanks for the answer, I just went with substr() to fix it, but I'll study through your notes to make sure I understand how it works as well.

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

Cool. I suspect you used more than just substr(), to preserve the day of the month. For example, this command --

echo substr("August 6",0,3);

-- would output just this --

>> Aug

-- without the " 6" at the end. Would you mind sharing your full solution here, for reference?