Jump to content

Limit echo to a number of characters


masgas

Recommended Posts

I'd like to print the latest messages from a forum in the index... the question is...

how do I limit the length of the topic's names so the table that holds it doesn't become too large and makes the whole design crazy!

is there anyway?

here is the echo I've got...

<?php echo "<a href='sec_sind/view_topic.php?id=$id' target='_self'>".$last_topic."</a>"?>

I want to limit $last_topic let's say to 10 chars max.

thank you in advance!
Link to comment
Share on other sites

In cases like this, substr() is your friend. It's great to run a function that will format it as you want. For instance, if you want 10 characters to be the absolute limit, you could always trim it to 7 and add elipsis as your final 3 characters, too:
[code]
<?php
function shortenMe($String, $limit = 10) {
  // default to 10 characters, but you can allow for whatever you wish
  if (strlen($String) > $limit) {
    $String = substr($String, 0, ($limit - 3)) . "...";
  }

  return $String;
}

$title = "Hello to all those of you who know how to shorten post title!";
echo shortenMe($title); // Hello t...
?>
[/code]

Hope this helps!
Link to comment
Share on other sites

[quote author=Jenk link=topic=114922.msg467754#msg467754 date=1163509995]
To prevent words being cut in half, you can use this simple step:
[code]<?php

$string = 'one two three four five six seven eight';

$part = substr($string, 0, 20);

echo substr($part, 0, strrpos($part, ' '));

?>[/code]
[/quote]

Good call, Jenk. There are some more complex ways to get this basic functionality into a trim function with a little more control, but that's an incredibly simple way to get the basic function down. Thanks for the addition.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.