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
https://forums.phpfreaks.com/topic/27202-limit-echo-to-a-number-of-characters/
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!
[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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.