简体   繁体   中英

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?

找到 ,也许对您来说更优雅。

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
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM