从这个简单的“修剪单词”功能中删除 HTML 标记


Strip HTML tags out of this simple "trim words" function

我在我正在处理的网站中使用以下函数;

function trim_text($input, $length) {
// If the text is already shorter than the max length, then just return unedited text.
if (strlen($input) <= $length) {
    return $input;
}
// Find the last space (between words we're assuming) after the max length.
$last_space = strrpos(substr($input, 0, $length), ' ');
// Trim
$trimmed_text = substr($input, 0, $last_space);
// Add ellipsis.
$trimmed_text .= '...';
return $trimmed_text;
}

然后像这样呼应;

echo trim_text($variableContainingContent, 100);

这工作正常,除非变量的前 100 个字符内是超链接。

有没有办法在回显此函数之前剥离它和任何其他 HTML?

在返回值上使用strip_tags:http://php.net/strip_tags

function trim_text($input, $length) {
    ...
    return strip_tags($trimmed_text);
}