Home > Backend Development > PHP Tutorial > How Can I Safely Truncate HTML-Tagged Strings in PHP While Preserving Content?

How Can I Safely Truncate HTML-Tagged Strings in PHP While Preserving Content?

Barbara Streisand
Release: 2024-12-20 11:46:09
Original
680 people have browsed it

How Can I Safely Truncate HTML-Tagged Strings in PHP While Preserving Content?

Removing HTML Tags from PHP Strings

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) . "...";
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template