donglu2008
donglu2008
2016-01-13 16:14

如何在codeigniter视图中截断字符串

已采纳

here is my controller which will get the url information from some model function and passed it to my view.

class MyController extends CI_Controller{

    public function __construct()
    {
        parent::__construct();

        //load the settings model
        //some model

        //load the text helper
        $this->load->helper('text');
    }

    public function index()
    {

        //call the model function to get the Url data
        $data['urllist'] = //call the model function and get the array and store it to urllist; 

        //load the view
        $this->load->view("myview",$data);

    }
}

and my view is

    <body>
        <?php

            /*
                //$longurl is an array element and its value is 
                some thing like 
                http://example.com/sdsds/sdsdsd/sdsdsdsd/sdsdsd/sdsdsd

                 i want to truncate it about 20 characters
            */
            $lurl=character_limiter($longurl, 20);
            echo $lurl; 

        ?>
    </body>

but it shows full url. can I use character_limiter in view? or I have to truncate it in my controller and passed it to view?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dsebywql016137 dsebywql016137 5年前

    In this case you had to use ellipsize() function from text helpers

    This function will strip tags from a string, split it at a defined maximum length, and insert an ellipsis.

    The first parameter is the string to ellipsize, the second is the number of characters in the final string. The third parameter is where in the string the ellipsis should appear from 0 - 1, left to right. For example. a value of 1 will place the ellipsis at the right of the string, .5 in the middle, and 0 at the left.

    An optional forth parameter is the kind of ellipsis. By default, … will be inserted.

    $str = 'this_string_is_entirely_too_long_and_might_break_my_design.jpg';
    
    echo ellipsize($str, 32, .5);
    

    Produces:

    this_string_is_e…ak_my_design.jpg
    

    ellislab.com official documentation

    点赞 评论 复制链接分享