CodeIgniter字符串截取
V层中加入:
$this->load->helper('sub_string');
使用:
<?php foreach($array as $key=>$value){?> <?php echo sub($array[$key]['字段名'],截取字节长度)?> <?php }?>
一下文件保存为:sub_string_helper.php,放入helper中即可
<?php /** * @desc 只截取中文字符 * @author ljf */ function sub($str, $len) { if(mb_strlen($str, 'UTF-8') != strlen($str)) //判断中是否包含中文, preg_match("/^[\x7f-\xff]+$/", $str)正则判断 { for($i = 0; $i < $len; $i ++) { $temp_str = substr ( $str, 0, 1 ); if (ord ( $temp_str ) > 127) { $i ++; if ($i < $len) { $new_str [] = substr ( $str, 0, 3 ); $str = substr ( $str, 3 ); } } else { $new_str [] = substr ( $str, 0, 1 ); $str = substr ( $str, 1 ); } } return join ( $new_str ); }else{ return $str; } }