您可以在控制器中执行此操作:
class Something extends CI_Controller{
public function index(){
$data['mytext'] = $this->_truncate('some text to truncate');
//truncated text will be available in the view as $mytext
$this->load->view('some_view', $data);
}
private function _truncate($text = NULL){
if($text){
$chars = 100;
$mytext = substr($text,0,$chars);
$mytext = substr($text,0,strrpos($text,' '));
return $mytext;
}
}
}
编辑:
您在视图中调用 db 东西,这完全不是 Codeigniter MVC。
这可能是 MVC 中的样子:
控制器
class Something extends CI_Controller{
public function index(){
$test_text = $this->my_model->get_text();
$data['test_text'] = $this->_truncate($test_text);
//truncated text will be available in the view as $test_text
$this->load->view('some_view', $data);
}
private function _truncate($text = NULL){
if($text){
$chars = 100;
$mytext = substr($mytext,0,$chars);
$mytext = substr($mytext,0,strrpos($mytext,' '));
return $mytext;
}
}
}
模型
class My_Model extends CI_Model{
public function get_text(){
//$this->db->get_where....or other db functions
return "testing text... this is only a test";
}
}
看法
<html>
<body>
<b><?php echo $test_text; ?></b>
</body>