-1

目前我使用这个脚本:

$tstring = strip_tags($nstitle);
if (strlen($tstring) > 65) {

    // truncate string
    $stringCut = substr($tstring, 0, 65);

    // make sure it ends in a word so assassinate doesn't become ass...
    $tstring = substr($stringCut, 0, strrpos($stringCut, ' ')).
               '.....<a href="">read more</a>'; 
}

如果我键入两行并将其用于剪切字符串,有时这将无法正常工作。但它给出了不同的结果,例如,在每行长度不同的情况下获得输出。如果全部相同,我想要所有行的长度相同。

4

1 回答 1

1

you can't make every input the same length (65) unless you add padding. since you are essentially chopping off everything after the last space, that last space might occur at a different position in a string. also, if there's no space, you might not get the expected result. so 1. check, and 2. pad.

    // truncate string
    $stringCut = substr($tstring, 0, 65);
    //make sure it can find a space
    if (strrpos($stringCut, ' ') > 0) {
        $stringCut = substr($stringCut, 0, strrpos($stringCut, ' '));
    }
    //then pad the string so its always 65 characters long
    while (strlen($stringCut) < 65) {
        $stringCut.="*";
    }

// make sure it ends in a word so assassinate doesn't become ass...
$tstring = $stringCut . '.....<a href="">read more</a>';
于 2013-08-16T02:13:59.130 回答