This article, will discuss multiple ways to trim a string by length in PHP.
Table Of Contents
Background
There are many situations where you need to limit the length of a string in PHP. For example, if you have a string like “This is a sample string”, and you want to trim it to only 10 characters, the resulting string should be “This is a”.
Solution: Using substr()
The substr() function in PHP is the most straightforward way to trim a string to a specific length. You can specify the desired length as the third parameter.
Let’s see the complete example,
<?php $originalString = "This is a sample string"; // Trim the string to 10 characters $trimmedString = substr($originalString, 0, 10); // Display the result echo $trimmedString; ?>
Output
This is a
In this example, substr($originalString, 0, 10) extracts a substring of the first 10 characters from $originalString.
Frequently Asked:
- Remove a SubString from a String in PHP
- Remove a string from an Array in PHP
- Remove Quotes and Double Quotes from a string in PHP
- Remove characters from String before a character in PHP
Additional Consideration
- Handling Multibyte Characters: If you’re working with multibyte character encodings like UTF-8, consider using mb_substr() instead of substr() to properly handle characters that may use more than one byte.
Let’s see the complete example,
<?php $originalString = "This is a sample string"; // Trim the string to 10 characters in a multibyte-safe way $trimmedString = mb_substr($originalString, 0, 10, 'UTF-8'); // Display the result echo $trimmedString; ?>
Output
This is a
mb_substr() works similarly to substr() but provides better support for multibyte characters, ensuring that characters are not incorrectly split.
- Adding Ellipsis: If you’re trimming text for display purposes (like in a user interface), you might want to append an ellipsis (…) to indicate that the text has been cut off.
Let’s see the complete example,
<?php $originalString = "This is a sample string"; // Check if the string needs to be trimmed if (strlen($originalString) > 10) { $trimmedString = substr($originalString, 0, 10) . '...'; } else { $trimmedString = $originalString; } // Display the result echo $trimmedString; ?>
Output
This is a ...
This code trims the string to 10 characters and adds an ellipsis if the original string is longer than 10 characters.
Summary
Trimming a string to a specific length in PHP can be effectively accomplished using substr() for simple scenarios or mb_substr() for handling multibyte character encodings. This functionality is particularly useful in scenarios like preparing excerpts, summaries, or fitting text into limited display areas. Adding an ellipsis for trimmed strings can enhance readability, especially in user interfaces.