0

Assume we have a string patterns also provide us a common vocabulary to describe solutions.

We substr() this string so we have patterns also provide us a common vocabulary to desc.

How to cut last string to patterns also provide us a common vocabulary to?

My way is:

$text = mb_substr($new['text'], 0, 100);

if(mb_substr($text, -1) != ' ') {

    $text_expl = explode(' ', $text);

    $text = implode(' ', array_splice($text_expl, 0, -1)) . ' ...';

}

Is there something nicer?

Maybe regualr expression or some PHP built-in function can do something similar?

s.webbandit
  • 16,332
  • 16
  • 58
  • 82
  • 1
    perhaps in another article lies your solution: http://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-chara – andrew Dec 19 '12 at 11:44

2 Answers2

4

This finds the last blank and takes the substring

$text = mb_substr($new['text'], 0, 100);
$i = mb_strrpos($text, ' ');
if ($i !== false)
    $text = mb_substr($text, 0, $i);
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
2

I'd use this one:

if (preg_match('/^.{1,26}\b/s', $str, $match))
{
    echo $line=$match[0];
}

This truncates the text the way you want. Also, when you specify more characters then there actually are in the string, it will just simply give you back the entire string. Which is the desired result alwell.

The following method works aswell, but gives you an error when there are less characters in the string than you specified.

// Needs more than 260 characters in $str
echo substr($str, 0, strpos($str, ' ', 260));

So since you need to wrap that in an if statement anyway, to check the length of $str, i'd go for the first option.

w00
  • 26,172
  • 30
  • 101
  • 147