I want to limit the length of text shown in php. What is the code in php? But i want to keep the full of text in database.

Dani AI

Generated

Brief summary: keep the full text in the database and truncate only when rendering. The substring example posted by has a syntax mistake (check parenthesis and the function call parameters), and is right to call out non-ASCII issues — trimming bytes instead of characters will corrupt UTF-8 text.

For multilingual input and emoji, use multibyte- or Unicode-aware routines rather than byte-based slicing; the PHP manual documents the mbstring and grapheme helpers for that purpose (mb_substr, grapheme_substr). Ensure the mbstring or intl extension is installed and test with real UTF-8 samples (accented letters, combined characters, emoji).

To avoid awkward breaks and broken HTML when shortening text: trim to the target length, then backtrack to the previous whitespace to preserve whole words and append an ellipsis if needed. For content that includes tags, perform HTML-aware truncation (walk text nodes and stop when the visible character limit is reached) so tags remain balanced — PHP's DOMDocument is a practical tool for that (DOMDocument). Alternatively use a well-maintained HTML-truncation library if the project needs more robustness.

Operational notes: for large lists it can be acceptable to ask the database for a shortened preview for performance, but verify the DB encoding matches the application (utf8mb4) to avoid surprises. Always keep the original in the DB, run automated tests with multilingual samples, and provide a clear "read more" link to the full content so readers can access the unmodified text.

Recommended Answers

All 2 Replies

Member Avatar for Member #900861

Hi cliffc,

Say you have a string called $fulltext, that is the full text string and you only want to display up to 20 chars of it to the user at the current time, then use the following code :

<?php

$fulltext = "This is the LM pilot. I'd like to take this opportunity to ask every person listening in, whoever and wherever they may be, to pause for a moment and contemplate the events of the past few hours and to give thanks in his or her own way."; // Full string to shorten

$shorttext = substr($fulltext), 0, 20); // Result : "This is the LM pilot"

echo $shorttext;

?>
commented: useful +4
Member Avatar for Member #120589

If you find non-ASCII acharacters in your text, you'll need to use:

$shorttext = mb_substr($fulltext, 0, 20, 'UTF-8');
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.