Get first n characters of a string

前端 未结 19 1379
萌比男神i
萌比男神i 2020-11-22 13:06

How can I get the first n characters of a string in PHP? What\'s the fastest way to trim a string to a specific number of characters, and append \'...\' if needed?

19条回答
  •  孤城傲影
    2020-11-22 13:34

    $yourString = "bla blaaa bla blllla bla bla";
    $out = "";
    if(strlen($yourString) > 22) {
        while(strlen($yourString) > 22) {
            $pos = strrpos($yourString, " ");
            if($pos !== false && $pos <= 22) {
                $out = substr($yourString,0,$pos);
                break;
            } else {
                $yourString = substr($yourString,0,$pos);
                continue;
            }
        }
    } else {
        $out = $yourString;
    }
    echo "Output String: ".$out;
    

提交回复
热议问题