How to Limit Characters in Magento

Sometimes a website’s product names, descriptions, reviews or other items can get too long and create issues with a layout. Luckily, Magento comes with a built in function called substr

An updated approach was added September 2016, it is recommended to use this method.

The function can be found at app/code/core/Mage/Core/Helper/String.php

public function substr($string, $offset, $length = null)

For example the product name by default looks like this:

<h1><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></h1>

Let’s assume that a maximum number of 26 characters can be displayed of a product’s name before the text wraps to the next line and we want to avoid that. We would pass the product name, an offset of 0 and the max length of 26.

<h1><?php echo substr($_helper->productAttribute($_product, $_product->getName(), 'name'),0, 26) ?></h1>

Or you can use the shorter form:

<h1><?php echo substr($_product->getName(),0, 26) ?></h1>

Additional Example:

Product Short Description – 100 characters

<?php echo substr($_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description'),0, 100) ?>

Or using shorter form:

<h2 class="product-name-short"><?php echo substr($_product->getShortDescription(),0,96); ?></h2>

Advanced Method

Update September 2016

There are potential issues with the original approach if the element has HTML character codes and these codes get cut off midway through. For example if a product name has &trade; but the cutoff ends in the middle and only displays &tr. Because of this it is recommended to use the following function provided by Sean Breeden. Note, adjust the '36' to your desired character count limit.


<?php
    function tokenTruncate($string, $your_desired_width) {
        $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
        $parts_count = count($parts);

        $length = 0;
        $last_part = 0;
        for (; $last_part < $parts_count; ++$last_part) {
            $length += strlen($parts[$last_part]);
            if ($length > $your_desired_width) { break; }
        }

        return implode(array_slice($parts, 0, $last_part));
    }

    $product_name = $_helper->productAttribute($_product, $_product->getName(), 'name');
    $product_name_limit = 36;
    
    if (strlen($product_name) < $product_name_limit) {
        echo $product_name;
    }
    else {
        echo tokenTruncate
            ($product_name, $product_name_limit) . '...';
    }
?>

Thanks to Magento Certified Developer Sean Breeden for his help with this code.