我的新闻列表内容太长了 我想通过字符串截取 但是有个问题是 如果是英文截取之后 显示半个单词 这样看起来不是很好 
请问有什么好的解决思路

解决方案 »

  1.   

    <p>&lt;?<br>&nbsp; function noBreakWord($string, $max){<br>&nbsp;&nbsp;&nbsp; $testChar = substr($string, $max, 1);<br>&nbsp;&nbsp;&nbsp; if ($testChar == " ") {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return substr($string, 0, $max); <br>&nbsp;&nbsp;&nbsp; } else {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while ($testChar&lt;&gt;" "){<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $testChar = substr($string, $max, 1);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if ($testChar == " "){<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return substr($string, 0, $max);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $max = $max-1;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp; }<br>?&gt;</p>
      

  2.   

    function noBreakWord($string, $max){
    $testChar = substr($string, $max, 1);
    if ($testChar == " ") {
    return substr($string, 0, $max);
    } else {
     while ($testChar !=" "){
    $testChar = substr($string, $max, 1);
    if ($testChar == " "){
    return substr($string, 0, $max);
    } else {
     $max = $max-1;
    }
    }
    }
    }
      

  3.   

    用 mb_substr ,根据字数截取
      

  4.   

    截止最多$maxWidth个半角字符,一个全角字符当两个半角字符计算
    代码测试通过function strMax($str, $maxWidth, $encoding='utf-8'){
    $strlen = mb_strlen($str); $newStr = '';
    for($pos = 0, $currwidth = 0; $pos < $strlen; ++$pos ){
    $ch = mb_substr($str, $pos, 1, $encoding);
    if ($currwidth + mb_strwidth($ch, $encoding) > $maxWidth)
    break; $newStr .= $ch;
    $currwidth += mb_strwidth($ch, $encoding) > 1 ? 2 : 1;
    } return $newStr;
    }$s = "123我是世界第一等";
    echo strMax($s, 6);