How can I remove three characters at the end of a string in PHP?

How can I remove three characters at the end of a string in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Truncating Strings: A Practical Guide to Removing Suffixes in PHP

In PHP, string manipulation often boils down to a simple question: how do you chop off exactly what you need without accidentally cutting into valid data? If you have a string like "abcabcabc" and your goal is to remove the last three characters to get "abcabc", the most direct tool is substr(). This function allows you to specify a starting position and a length, giving you precise control over the substring extraction.

To remove the final three characters from a string stored in a variable $str, you calculate the new end position by subtracting 3 from the string's total length. You can retrieve this length using strlen(). The logic is straightforward: if the string is 9 characters long, you want to keep only the first 6.

$str = 'abcabcabc';
$length = strlen($str);
$newLength = $length - 3;

$result = substr($str, 0, $newLength);

echo $result; // Outputs: abcabc

This approach is robust because it relies on the actual length of the string rather than relying on assumptions about content. However, a critical pitfall emerges when the string is shorter than three characters. If you attempt to subtract 3 from a length that is less than or equal to 3, $newLength becomes zero or negative. While substr() handles a length of zero gracefully (returning an empty string), passing a negative start position can cause unexpected behavior depending on the PHP version and specific context, though typically it treats negative starts as relative to the end of the string.

$shortStr = 'ab';
$len = strlen($shortStr); // 2
$subLen = $len - 3; // -1

echo substr($shortStr, 0, subLen); 
// In older PHP versions or specific contexts, this might throw a warning or return an empty string.

A safer pattern is to check the length before calculating the new substring. If the string is shorter than the number of characters you intend to remove, you should simply return the original string or handle that edge case explicitly. This prevents logic errors in downstream processing where an empty string might be mistaken for a valid result.

function truncateString($str, $charsToRemove) {
    if (strlen($str) <= $charsToRemove) {
        // Handle case where there aren't enough characters to remove
        return ''; 
        // Or return $str if you prefer to keep the original content intact
    }
    
    return substr($str, 0, strlen($str) - $charsToRemove);
}

Another common scenario involves removing a specific suffix rather than a raw count of characters. For example, stripping the .json extension or a query string. While substr() works for fixed positions, functions like rtrim() are designed to remove characters from the right side based on a pattern. However, rtrim() removes any character found in the provided mask until it hits one not in the mask. If you use rtrim($str, '.'), it will strip all trailing dots, which is rarely what you want if you only intend to remove three characters or a specific file extension. You must be precise about whether you are removing a count of bytes/characters or a semantic suffix.

If you are working within a Laravel project, string manipulation often gets delegated to the Str facade. While the core PHP functions remain relevant for performance-critical loops or when dealing with raw data, Laravel provides helper methods that can offer cleaner syntax. For instance, $str->substr($length) is not a built-in method on the Stringable trait in the same way substr() is available globally; you would typically stick to the native function or use Str::slice(). The Str facade is particularly useful when chaining operations, but for a simple truncation, the native substr() function remains the most performant and readable choice.

Ultimately, the decision to use substr() with an offset calculation versus a conditional check depends on your data integrity requirements. If the input is trusted to always be long enough, the one-liner substr($str, 0, -3) works in many PHP versions by treating the negative length as "from the end." However, relying on negative offsets can introduce version-specific inconsistencies. Explicitly calculating the length ensures your code behaves predictably across all environments, from legacy shared hosting to modern containerized applications.

For developers managing large datasets or processing high-throughput logs where every millisecond counts, avoiding unnecessary function calls inside loops is vital. Calculating strlen() once and reusing that value is a micro-optimization, but in tight loops, it prevents repeated system calls to determine string length. Always profile your code if performance becomes a bottleneck before assuming the simplest syntax is the fastest.

Our network