PHP: Truncate from Left

Posted on 2011-05-04
Last Modified: 2012-05-11
Using PHP, how can I truncate text on the left side?

$str = 'This is a test and only a very long test to see if this works'

echo truncate_left($str,10);
// should echo 'this works';

function truncate_left($str, l) {
return ($str);


Open in new window

Question by:hankknight
    LVL 9

    Expert Comment

    substr($str, 0, 10)

    will return 10 characters, starting from 0.

    LVL 16

    Author Comment

    Yea, but I want to truncate in the other direction.

    This is a test and only a very long test to see if this works
    Should become
    this works

    Test the code I posted and you will see what I mean.
    LVL 27

    Accepted Solution

    Try this:

    $str = 'This is a test and only a very long test to see if this works';
    print truncate_left($str,10);
    // should echo 'this works';
    function truncate_left($string,$count) {
     $string = substr($string, -$count, $count);
     return $string;

    Open in new window


    Featured Post

    Better Security Awareness With Threat Intelligence

    See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

    Join & Write a Comment

    Suggested Solutions

    Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
    Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
    Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now