php在mb_substr()之后找到最近的空格字符

时间:2011-11-03 11:19:59

标签: php string utf-8 mbstring

我需要将字符串切割成大约160个字符,但我想通过最近的空格字符进行剪切。使用UTF-8字体(mb_函数)会使任务变得更糟。我的代码如下:

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

有谁知道更优雅的方式?

2 个答案:

答案 0 :(得分:2)

找到this,也许对你来说更加优雅。

答案 1 :(得分:1)

我做这样的事情:

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