Jump to content

Help with substr()


benji87

Recommended Posts

Hi all ive currently got some news displaying which i have limited to 75 characters using the substr() function so the user can click and read more. Im just wondering if there is a way to get the script to not chop off the end of words. As every bit of news will be different lengths there is no garuntee that it will show whole words when it comes to the end of the string of 75 charcs.

For example if i have news with the first sentance being displayed i want it to show like this:

This is the first sentance of this news article.

and not this:

This is the first sentance of this ne

Can anyone help?
Link to comment
Share on other sites

that should do :-)
[code]
<?
function filter_wordlimit($string, $length = 50, $ellipsis = '...'){
return count($words = preg_split('/\s+/', ltrim($string), $length + 1)) > $length ? rtrim(substr($string, 0, strlen($string) - strlen(end($words)))) . $ellipsis : $string;
}
?>
[/code]
Link to comment
Share on other sites

Take a look at [url=http://www.php.net/wordwrap]wordwrap()[/url] and use it together with [url=http://www.php.net/explode]explode()[/url]

ex:
[code=php:0]$string = 'Hi all ive currently got some news displaying which i have limited to 75 characters using the substr() function so the user can click and read more.';

$string = wordwrap($string, 75, "|", 1);
list($string) = explode('|', $string);

echo $string;[/code]
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.