我的网站上有一个评论系统,一些用户写了很长的评论,超过500个字符,我需要在200之后剪切它并添加选项“看到更多”.问题是用户可以使用< a> test< / a>在某些情况下,200个字符的限制会削减中间的标记,例如< a> t或< a或< a>测试< /如果上述任何情况发生,则限制应延长至结束html标签的所以ex< a> test< / a>
我有这个代码:
function truncate($string,$length=200,$append="…") { $string = trim($string); if(strlen($string) > $length) { $string = wordwrap($string,$length); $string = explode("\n",$string,2); $string = $string[0] . $append; } return $string; }
知道如何制作这个吗?
谢谢
好吧,我想我做到了.如果有人有任何建议,请随时修改此答案或评论.
原文链接:https://www.f2er.com/php/134243.htmlfunction cut_text($string,$length = 350,$append = "…") { $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",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",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,2); $string = $string[0] . $append; } } return $string; }