0

Possible Duplicate:
Shorten String in PHP (full words only)

Below substr which iam using . Which echo first 38 characters from my database. This code breaking the word which is at end .

<?php echo substr(ucfirst($row['metadesc']),0,38); ?>...

which output like this.

news for today was null try tomo

how to stop the string after 38 characters after the end of word.

output should be like this

news for today was null try tomorrow
Community
  • 1
  • 1
PHP
  • 445
  • 1
  • 10
  • 20

3 Answers3

1
function TrimString($String, $Length)
{
    if(strlen($String) > $Length)
    {
        $Temp[0] = substr($String, 0, $Length);
        $Temp[1] = substr($String, $Length);
        $SpacePos = strpos($Temp[1], ' ');
        if($SpacePos !== FALSE)
        {
            return $Temp[0].substr($Temp[1], 0, $SpacePos);
        }
    }
    return $String;
}
mdziekon
  • 3,531
  • 3
  • 22
  • 32
0
function substrword($str, $begin, $length) 
{
    if (($begin + $length) < strlen($str)) {    
            return substr($str, $begin, $length).current(explode(' ', substr($str, $length))).'...';
    }
    return $str;
}
Wouter J
  • 41,455
  • 15
  • 107
  • 112
0

You can use this regex:

preg_match('/^(.{1,38})\b/u', $string, $matches);

Your string will be:

$matches[1]
Peter Adrian
  • 279
  • 1
  • 5