note 49714 added to function.strlen

From: Date: Sun, 06 Feb 2005 14:32:14 +0000
Subject: note 49714 added to function.strlen
Groups: php.notes 
Request: Send a blank email to php-notes+get-84581@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: 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); } ---- Manual Page -- http://www.php.net/manual/en/function.strlen.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+49714 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+49714&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49714&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+49714&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+49714&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+49714&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+49714&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#84581) next »