gpt4 book ai didi

php - 在 html 结束标记后剪切文本

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:17 26 4
gpt4 key购买 nike

我的网站有一个评论系统,有些用户写的评论很长,超过 500 个字符,我需要在 200 个字符后将其剪切并添加“查看更多”选项。问题是用户可以使用 <a>test</a>标签,在某些情况下,200 个字符的限制会在中间切割标签,例如 <a>t<a<a>test</如果发生上述任何情况,限制应延伸到 html 标记的末尾,例如 <a>test</a>

我有这个代码:

function truncate($string,$length=200,$append="&hellip;") {
$string = trim($string);

if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}

return $string;
}

知道怎么做吗?

谢谢

最佳答案

嗯,我想我做到了。如果有人有任何建议,请随时修改此答案或评论。

function cut_text($string, $length = 350, $append = "&hellip;")
{

$string = trim($string);
$string_length = strlen($string);
$original_string = $string;
if ($string_length > $length) {
$remaining_chars = $string_length - $length;
if (strpos($string, '<') !== false && strpos($string, '>') !== false) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
$fillimi = substr_count($string, '<');
$fundi = substr_count($string, '>');
if ($fillimi == $fundi) {
$string = $string;
} else {
$i = 1;
while ($i <= $remaining_chars) {
$string = wordwrap($original_string, $length + $i);
$string = explode("\n", $string, 2);
$new_remaining_chars = $string_length - ($length + $i);
if ($new_remaining_chars > 0) {
$string = $string[0] . $append;
} else {
$string = $string[0];
}
$fillimi = substr_count($string, '<');
$fundi = substr_count($string, '>');
if ($fillimi == $fundi) {
$string = $string;
break;
}
$i++;
}
}
} else {
$string = trim($string);

$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;

}
}
return $string;
}

关于php - 在 html 结束标记后剪切文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27655810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com