Search code examples
phpstringutf-8mbstring

php finding closest space char after mb_substr()


i need to cut the string approximately at 160 characters, but i want to do the cut off through closest space character. The task is worsened by working UTF-8 font (mb_ function). My code is following:

<?php
function mb_strrev($str, $encoding='UTF-8'){

   return mb_convert_encoding( strrev( mb_convert_encoding($str, 'UTF-16BE', $encoding) ),

$encoding, 'UTF-16LE');
}

$in = mb_strpos(mb_strrev(trim(mb_substr($mysring, 0, 165))), ' ');

$new = mb_substr(mb_strrev(trim(mb_substr($mysring, 0, 165))), $in, 165);

mb_strrev($new);
?>

Does anyone know more elegant way?


Solution

  • I'd do something like this:

    <?php  
    function approx_len($str,$len) {  
    $x = explode(" ",$str);  
    $y = count($x);  
    $newlen = '';  
    for ($i = 0; $i < $y; $i++) {  
    $this_x = $x[$i]. ' ';  
    if (strlen($newlen.$this_x) > $len) $i = $y;  
    else $newlen = $newlen.$this_x;  
    }  
    return $newlen;  
    }  
    $x = approx_len("aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa",160);  
    echo $x;  
    echo '<br />';  
    echo strlen($x);  
    //returns 156
    ?>