note 54091 deleted from function.preg-match by colder

From: Date: Mon, 18 Jun 2007 18:23:21 +0000
Subject: note 54091 deleted from function.preg-match by colder
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-127605@lists.php.net to get a copy of this message
Note Submitter: tom at depman dot com ---- 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... */ ?>

« previous php.notes (#127605) next »