-10

How to make string shorter by cut it on the last word?

like example, allowed symbols are 10, and echo only these words which fits in this limit.

$string = 'Hello Hello John Doe'

// Limit 10. Expected result:
$string = 'Hello'

// Limit 12. Expected result:
$string = 'Hello Hello'
...

All I can find in manual is cutting string by symbols, not by words. There are some custom functions to do so, but maybe there are php command for this?

Gediminas Šukys
  • 7,101
  • 7
  • 46
  • 59

3 Answers3

2

This should work:

$str = "i have google too";
$strarr = explode(" ", $str);

$res = "";

foreach($strarr as $k) 
{
    if (strlen($res.$k)<10)
    {
        $res .= $k." ";
    }
    else
    {
        break;
    };
}

echo $res;

http://codepad.org/NP9t4IRi

Milan Halada
  • 1,943
  • 18
  • 28
1

Edit: update version to cope with word breaks better.

This shouldn't be too difficult. Truncate to the maximum length, then truncate to the last space. Add an adjustment for lengths that fall on the end of words

<?php
$str = "Hello Hello My name is Hal";
for ($i = 3; $i <30;$i++) {
echo "'".trunc($str,$i)."'\n";
}

function trunc($str, $len) {
$str.=' ';
$out = substr($str,0,$len+1);
$out = substr($out,0,strrpos($out,' '));
return trim($out); 
}

Here's a codepad version

1

Tried to edit Mike's answer, to fix the last word thing, but was not able to.

So here is his solution with the fix:

$str = "Hello Hello My name is Hal";
$len = 10;

if ( strlen( $str ) > $len )
{
    $out = substr($str,0,$len);
    if ( $str[$len] != ' ')
    {
        $out = substr($out,0,strrpos($out,' '));
    }
}

echo $out; // Hello