Limiting Characters in a Text String

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gjb79
Forum Commoner
Posts: 96
Joined: Fri Jul 18, 2003 6:35 am
Location: x <-- (DC)
Contact:

Limiting Characters in a Text String

Post by gjb79 »

Hi,
I'm wondering, is there any easy way to limit the amount of characters that display in a text string and add ... at the end?

example:
I went to the store today
I went to the stor...

How it will be used:
I have an array, built from a database, that is being used to fill a drop down menu. The menu is too wide, so I want to limit the text characters to display 20-30 characters. This way if a text string from the database is too long, it wont make the window wider than I want it.

Here is the loop and coding that builds my drop down menu:

Code: Select all

<select name="select" onChange="MM_jumpMenu('parent',this,0)">
  <option value="" <?php if (!(strcmp("", $row_BookTitles&#1111;'ID']))) &#123; if ($BookSelected != 1) &#123;echo "SELECTED";&#125;&#125; ?>>Select a Book</option>
<?php do &#123;  ?>
  <option value="index.php?bookSelected=1&BookID=<?php echo $row_BookTitles&#1111;'ID']?>"<?php if (!(strcmp($row_BookTitles&#1111;'ID'], $row_BookTitles&#1111;'ID']))) &#123; if ($HTTP_GET_VARS&#1111;'BookID'] == $row_BookTitles&#1111;'ID']) &#123; echo "SELECTED"; &#125; else &#123; echo "";&#125;&#125; ?>><?php echo $row_BookTitles&#1111;'BTitle']?></option>
<?php &#125; while ($row_BookTitles = mysql_fetch_assoc($BookTitles));
  $rows = mysql_num_rows($BookTitles);
  if($rows > 0) &#123;
      mysql_data_seek($BookTitles, 0);
	  $row_BookTitles = mysql_fetch_assoc($BookTitles);
  &#125;
?>
</select>
The text string is within this variable:

Code: Select all

<?php echo $row_BookTitles&#1111;'BTitle']?>
Thanks for your help!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
gjb79
Forum Commoner
Posts: 96
Joined: Fri Jul 18, 2003 6:35 am
Location: x <-- (DC)
Contact:

Brilliant!

Post by gjb79 »

Excellent. I didn't know about substr and I couldn't figure out what cutting characters short might be called to look it up.

What I can't find is a way to add "..." at the end of only the characters cut short. Any ideas?

:D
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

using the codes I wrote there, you can check the return of the function, and it's matches.. if the length of the original is different than the lenght of the new, it was chopped.
Post Reply