Tutorial: How to Limit Characters to Display in a String using PHP
About How to Limit Characters to Display in a String using PHP
This is a tutorial on How to Limit Characters to Display in a String using PHP. We will use substr() function that will return the part of the string. We will also use substr_replace function to replace the part of the string.
Using substr()
The first method is to use the substr() function. The substr() function returns a part of a string.
Syntax:
substr(string, start, length)
PARAMETER | DESCRIPTION |
---|---|
string | Required. Specifies the string to return a part of |
start | Required. Specifies where to start in the string |
length | Optional. Specifies the length of the returned string. Default is to the end of the string. |
Example:
<?php $string = "How to Limit Characters to Display in a String using PHP"; echo substr($string, 0, 30); ?>
The above code will output How to Limit Characters to Dis.
Using substr_replace
The second method is using substr_replace function. The substr_replace() function replaces a part of a string with another string.
Syntax:
substr_replace(string, replacement, start, length)
PARAMETER | DESCRIPTION |
---|---|
string | Required. Specifies the string to check |
replacement | Required. Specifies the string to insert |
start | Required. Specifies where to start replacing in the string |
length | Optional. Specifies how many characters should be replaced. Default is the same length as the string. |
Example:
You wanted only to display 25 characters and replace the remaining characters with “…”.
<?php $string = "How to Limit Characters to Display in a String using PHP"; echo substr_replace($string, '...', 25); ?>
The above code will output This tutorial tackles on.

That ends this tutorial. Happy Coding!