How to Remove HTML Tags from String in Laravel 11

Removing HTML tags from a string in Laravel 11 can be accomplished using various methods, ranging from simple PHP functions to Laravel’s own features. Let’s explore a few approaches:

  1. Using PHP’s strip_tags function: Laravel allows you to use PHP functions directly within your codebase. The strip_tags function is a simple and effective way to remove HTML tags from a string. You can utilize it like so:
$cleanString = strip_tags($htmlString);

This line will remove all HTML tags from the $htmlString, leaving you with just the plain text.

  1. Using Laravel’s strip_tags helper function: Laravel provides helper functions to streamline common tasks. The strip_tags helper function works similarly to PHP’s strip_tags function, but it’s more Laravel-friendly:
use Illuminate\Support\Str;

$cleanString = Str::stripTags($htmlString);

This accomplishes the same task as the previous method but uses Laravel’s helper function instead.

  1. Using Regular Expressions: While not always recommended for parsing HTML, a simple regular expression can also be used to strip HTML tags:
$cleanString = preg_replace('/<[^>]*>/', '', $htmlString);

This regular expression matches any HTML tag and replaces it with an empty string, effectively removing it from the string.

  1. Using Laravel Blade’s strip_tags directive: If you’re working within a Blade template and need to sanitize user input, Laravel Blade provides a strip_tags directive:
{{ strip_tags($htmlString) }}

This will output the $htmlString with all HTML tags removed when the Blade template is rendered.

  1. Using Laravel’s Input Sanitization Middleware: If you’re dealing with user input in your controller, it’s a good practice to sanitize input to prevent XSS attacks. Laravel middleware provides a convenient way to sanitize input before it reaches your controller. You can create a custom middleware or use Laravel’s built-in middleware:
use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;

protected $middlewareGroups = [
    'web' => [
        // Other middleware...
        ConvertEmptyStringsToNull::class,
    ],
];

By configuring the ConvertEmptyStringsToNull middleware, Laravel automatically converts empty strings to null, effectively removing HTML tags.

These methods provide different approaches to removing HTML tags from a string in Laravel 11, allowing you to choose the one that best fits your specific use case and coding style.

Leave a Reply