Shorten a text string in PHP

前端 未结 9 2321
暗喜
暗喜 2020-12-20 02:32

Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:

$string = \"this is a string\";

相关标签:
9条回答
  • 2020-12-20 03:20

    If you want an abstract for the first 10 words (you can use html in $text, before script there is strip_tags) use this code:

    preg_match('/^([^.!?\s]*[\.!?\s]+){0,10}/', strip_tags($text), $abstract);
    echo $abstract[0];
    
    0 讨论(0)
  • 2020-12-20 03:20

    My function has some length to it, but I like to use it. I convert the string int to a Array.

    function truncate($text, $limit){
        //Set Up
        $array = [];
        $count = -1;
        //Turning String into an Array
        $split_text = explode(" ", $text);
        //Loop for the length of words you want
        while($count < $limit - 1){
          $count++;
          $array[] = $split_text[$count];
        }
        //Converting Array back into a String
        $text = implode(" ", $array);
    
        return $text." ...";
    
      }
    

    Or if the text is coming from an editor and you want to strip out the HTML tags.

    function truncate($text, $limit){
        //Set Up
        $array = [];
        $count = -1;
        $text = filter_var($text, FILTER_SANITIZE_STRING);
    
        //Turning String into an Array
        $split_text = preg_split('/\s+/', $text);
        //Loop for the length of words you want
        while($count < $limit){
          $count++;
          $array[] = $split_text[$count];
        }
    
        //Converting Array back into a String
        $text = implode(" ", $array);
    
        return $text." ...";
    
      }
    
    0 讨论(0)
  • 2020-12-20 03:24

    substr let's you take a portion of string consisting of exactly as much characters as you need.

    0 讨论(0)
  • 2020-12-20 03:24

    If you want to get a string with a certain number of characters you can use substr, i.e.

    $newtext = substr($string,0,$length); 
    

    where $length is the given length of the new string.

    0 讨论(0)
  • 2020-12-20 03:25
    if (strlen($yourString) > 15) // if you want...
    {
        $maxLength = 14;
        $yourString = substr($yourString, 0, $maxLength);
    }
    

    will do the job.

    Take a look here.

    0 讨论(0)
  • 2020-12-20 03:28

    You can use this

    substr()
    

    function to get substring

    0 讨论(0)
提交回复
热议问题