How to Limit Characters to Display in a String using PHP

Using substr()

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:
  1. <?php
  2. $string = "How to Limit Characters to Display in a String using PHP";
  3. echo substr($string, 0, 30);
  4. ?>
The above code will output How to Limit Characters to Dis

Using substr_replace

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 to only display 25 characters and replace the remaining characters with "...".
  1. <?php
  2. $string = "How to Limit Characters to Display in a String using PHP";
  3. echo substr_replace($string, '...', 25);
  4. ?>
The above code will output This tutorial tackles on ... That ends this tutorial. Happy Coding :)

Add new comment