Home >Backend Development >PHP Tutorial >How Can I Safely Truncate HTML-Tagged Strings in PHP While Preserving Content?
Stripping out HTML tags from a PHP string is essential when displaying user-generated content or data retrieved from untrusted sources, to prevent malicious code injection or incorrect formatting. In this case, an HTML string needs to be truncated while maintaining its content without any HTML tags.
The strip_tags() function provides an efficient solution for this task. It removes all HTML and PHP tags from a string, while preserving the content within them. By utilizing this function, we can effectively eliminate the unwanted HTML code from the database entry.
The implementation involves combining strip_tags() with substr(). First, strip_tags() is applied to the database entry, removing all HTML tags. Subsequently, substr() is used to truncate the processed string to the desired length, in this case, the first 100 characters.
$cleaned_text = strip_tags($row_get_Business['business_description']); echo substr($cleaned_text, 0, 110) . "...";
By employing this method, we ensure that the database entry is stripped of HTML tags, and only the desired portion of the content is displayed. This approach effectively addresses the issue of displaying HTML code within truncated text, providing a cleaner and safer user experience.
The above is the detailed content of How Can I Safely Truncate HTML-Tagged Strings in PHP While Preserving Content?. For more information, please follow other related articles on the PHP Chinese website!