Limit Characters to Display in a String using PHP

By CampCodes Administrator

Published on:

How to Limit Characters to Display in a String using PHP

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)

PARAMETERDESCRIPTION
stringRequired. Specifies the string to return a part of
startRequired. Specifies where to start in the string
lengthOptional. 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)

 

PARAMETERDESCRIPTION
stringRequired. Specifies the string to check
replacementRequired. Specifies the string to insert
startRequired. Specifies where to start replacing in the string
lengthOptional. 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.

READ ALSO:   Add Extra Time In Current Day in PHP
How to Limit Characters to Display in a String using PHP
How to Limit Characters to Display in a String using PHP

That ends this tutorial. Happy Coding!

Leave a Comment