使用 PHP 限制 HTML 文本中特定数量的字符

发布于 2024-11-05 06:48:14 字数 378 浏览 0 评论 0原文

我正在使用CKEditor并且我已经找到/修改了一个计算字符的插件。

我有高级用户和基本用户。 基本用户限制为 1000 个字符,高级用户没有限制,但基本用户可以编写全文以进行预览/测试等(这是客户规范,因此无法更改)。

当我在 CKEditor 中显示 1000 个字符中的 1500 个时,我想在 DB 中保存 1500 个字符,但在文本输出中仅显示其中的 1000 个

但 strlen 和相关函数将 HTML 标签计为字符,我不希望这样。我也不想删除它们,因为我会丢失格式。

有没有办法确保应用限制,但所有标签都将保留(在 PHP 中)

谢谢...

I am using the CKEditor and I have found/modified a plugin that counts the characters.

I have premium and basic users.
The basic user is limited to 1000 characters and the premium is unlimited, but basic can write full text for preview/tests etc. (it's clients spec, so can't change that).

While I am showing e.g. 1500 of 1000 characters in CKEditor, I want to save in DB 1500 chars but show only the 1000 of them on text output.

But strlen and related functions are counting the HTML tags as chars and I don't want this. Also I don't want to strip them, because I will lose the format.

Is there a way to be sure that the limit will be applied but also all the tags will be remain (in PHP)??

Thanks...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

镜花水月 2024-11-12 06:48:14

try

$theHTML='<h2>Hello!</h2>';
$length = strlen ( strip_tags($theHTML) ); //Should be 6
echo "The non-HTML length is: $length";

这只会剥离标签以进行计数。标签实际上永远不会丢失。

更新

根据webbiedave的建议,它确实应该是

$theHTML='<h2>Hello!</h2>';
$length = strlen ( shtml_entity_decode(strip_tags($theHTML)) ); //Should be 6

//This will not trigger since only the text "Hello!" is only 6 chars.    
if ($length > 10) die('ERROR'); 

echo $theHTML; //Will echo full HTML, even though we checked the length without HTML.

try

$theHTML='<h2>Hello!</h2>';
$length = strlen ( strip_tags($theHTML) ); //Should be 6
echo "The non-HTML length is: $length";

This will only strip the tags for purposes of counting. The tags never actually get lost.

Update

According to webbiedave's suggestion it really should be

$theHTML='<h2>Hello!</h2>';
$length = strlen ( shtml_entity_decode(strip_tags($theHTML)) ); //Should be 6

//This will not trigger since only the text "Hello!" is only 6 chars.    
if ($length > 10) die('ERROR'); 

echo $theHTML; //Will echo full HTML, even though we checked the length without HTML.
萝莉病 2024-11-12 06:48:14

我之前使用的这段代码: http://www.php.net/manual/en/function.substr.php#92063 该函数减去字符(例如 0 到 1000)但留下HTML 标签完好无损。

This piece of code I used earlier: http://www.php.net/manual/en/function.substr.php#92063 this function substracts the characters (fe. 0 to 1000) but leaves the HTML tags intact.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文