Skip to content
PHP Logo

How can the strlen() function be used to limit the output of a string in PHP?

To limit the output of a string in PHP using the strlen() function, you can simply check the length of the string and truncate it if it exceeds a certain limit. This can be useful when displaying content such as user comments or product descriptions to prevent them from taking up too much space on the page.

php
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$limit = 20;

if(strlen($string) > $limit){
    $string = substr($string, 0, $limit) . "...";
}

echo $string;