1

I have used PHP, json and API Cache to successfully show a Facebook Feed Message on a website. However some of the messages are too long to fit into the space provided on the website.

Does anyone know if there is a way to limit the amount of Words or Characters the message will display?

Best scenario would to have the message show fully if below limit and then show certain amount of words or characters i over followed by [...] read full post @pagename

Then I can add the link to the Facebook post to view full message. I know how to add the post link and text, just need to scale the message down.

Here is the PHP code I am using:

<?php $fb_message = $fb_json->data[0]->message; ?>
<?php echo $fb_message; ?>

Any help would be greatly appreciated.

Thanks, Steve


Thanks to James Pearce I was able to get it working using the following code:

<?php $fb_message = $fb_json->data[0]->message; $truncated = substr($fb_message, 0, strrpos(substr($fb_message, 0, 100), ' ')); echo $truncated . '...'; ?>

It works if the message is more than 100 characters, but if it is less it will only show the first word and no more....?

Anyone know what I am doing wrong?

Kara
  • 6,115
  • 16
  • 50
  • 57

2 Answers2

0

There is no way to get the Facebook API to truncate the string for you. However, there are lots of ways you can do this in PHP.

One simple way is using the wordwrap function (http://www.php.net/wordwrap) and taking everything before the first line break.

See also How to Truncate a string in PHP to the word closest to a certain number of characters?

This seems work fine:

<?php 
    $fb_message = $fb_json->data[0]->message;
    echo array_shift(explode("\n", wordwrap($fb_message, 100)));
?>
Community
  • 1
  • 1
James Pearce
  • 2,332
  • 15
  • 14
  • Thanks James, that headed me down the right path. I have it working for messages that are longer than 100 characters, but not working if shorter. I posted the code and new problem under my original one. Any further help would be great. – Steven Beatty Nov 16 '12 at 04:53
0

Here is the code I used to check how long the Facebook "message" field is and then to either truncate it, if it is longer than 100 characters, or display the whole thing if it is short enough:

$post->message = $fbdata->data[0]->message; 
$messageLength = strlen($post->message);
if ($messageLength < 100) {
     $outputMessage = $post->message; 
} else {
     $outputMessage = substr($post->message, 0, strrpos(substr($post->message, 0, 100), ' ')) . ' ...'; 
}
echo $outputMessage;
TheLibzter
  • 768
  • 8
  • 8