note 54091 added to function.preg-match

From: Date: Thu, 23 Jun 2005 13:14:45 +0000
Subject: note 54091 added to function.preg-match
Groups: php.notes 
Request: Send a blank email to php-notes+get-90838@lists.php.net to get a copy of this message
There have been several examples of abbreviating strings or an ellipse function like some may call it. Of course I couldn't find any until after I wrote this, so thought I'd share with you. Basically what this does is takes a long string (like a TEXT from MySQL) and shortens it to give a quick display of the text. But instead of chopping it in the middle of the word it looks for a period or a space using preg_match and chops there. Hope this helps someone. <?php // the maximum length of characters of text to display $MAX_LEN = 50; $text_to_display = "Connect to a MySQL database or get some other source for a long string you'd like to display but don't want to chop the words in half"; /* check to see if the text is longer than our wanted length and if so find the last word less than the $MAX_LEN and display the string up to that last word. If youre using PHP version 4.3 or above you may need to specify PREG_OFFSET_CAPTURE to get the preg_match to work. */ function abreviated_text( $text_to_display, $MAX_LEN=30 ){ if ( strlen($text_to_display) > $MAX_LEN ){ preg_match ( "/.* /", substr($text_to_display,0,$MAX_LEN), $found ); $text_to_display_abr = substr("{$found[0]}",0,-1); } // if abreviation took place if ( $text_to_display_abr ) // do something special like add a <a href=""> tag return $text_to_display_abr."..."; else // simply display the text if it does not exceed the length return $text_to_display; } // use as echo abreviated_text($text_to_display,$MAX_LEN); /* prints out: Connect to a MySQL database or get some other... instead of: Connect to a MySQL database or get some other sour... */ ?> ---- Manual Page -- http://www.php.net/manual/en/function.preg-match.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+54091 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54091&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54091&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54091&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54091&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54091&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54091&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+54091&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#90838) next »