note 49714 modified in function.strlen by thiago

From: Date: Wed, 11 Feb 2009 14:05:40 +0000
Subject: note 49714 modified in function.strlen by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-150483@lists.php.net to get a copy of this message
Hi, if you want to trim a sentence to a certain number of characters so that it is displayed nicely in a HTML page (in a table for instance), then you actually want to count the number of characters displayed rather than the actual number of characters of the string. For instance: "L&agrave; bas" should really be 5 character long, rather than 10. Also you don't want to cut a special char in the middle. For instance: If 3 is the maximum number of characters, "L&agrave; bas" should be cut as "L&agrave; ..." and not "L&a..."; So here is a simple method to dothat: <?php function nicetrim ($s) { // limit the length of the given string to $MAX_LENGTH char // If it is more, it keeps the first $MAX_LENGTH-3 characters // and adds "..." // It counts HTML char such as &aacute; as 1 char. // $MAX_LENGTH = 22; $str_to_count = html_entity_decode($s); if (strlen($str_to_count) <= $MAX_LENGTH) { return $s; } $s2 = substr($str_to_count, 0, $MAX_LENGTH - 3); $s2 .= "..."; return htmlentities($s2); } ?> --was-- Hi, if you want to trim a sentence to a certain number of characters so that it is displayed nicely in a HTML page (in a table for instance), then you actually want to count the number of characters displayed rather than the actual number of characters of the string. For instance: "L&agrave; bas" should really be 5 character long, rather than 10. Also you don't want to cut a special char in the middle. For instance: If 3 is the maximum number of characters, "L&agrave; bas" should be cut as "L&agrave; ..." and not "L&a..."; So here is a simple method to dothat: function nicetrim ($s) { // limit the length of the given string to $MAX_LENGTH char // If it is more, it keeps the first $MAX_LENGTH-3 characters // and adds "..." // It counts HTML char such as &aacute; as 1 char. // $MAX_LENGTH = 22; $str_to_count = html_entity_decode($s); if (strlen($str_to_count) <= $MAX_LENGTH) { return $s; } $s2 = substr($str_to_count, 0, $MAX_LENGTH - 3); $s2 .= "..."; return htmlentities($s2); } http://php.net/manual/en/function.strlen.php

« previous php.notes (#150483) next »