Laravel Tutorials

Process Markdown Securely with Laravel's inlineMarkdown Method

Published
Process Markdown Securely with Laravel's inlineMarkdown Method image

Laravel enhances string processing capabilities with the inlineMarkdown method, providing secure transformation of GitHub-flavored Markdown into inline HTML with built-in XSS protection and customizable security options.

The inlineMarkdown method enables safe Markdown conversion with granular control over security settings:

use Illuminate\Support\Str;

// Basic conversion
$html = Str::inlineMarkdown('**Laravel**');
// Result: <strong>Laravel</strong>

// Secure conversion with options
$html = Str::inlineMarkdown(
    'Inject: <script>alert("Hello XSS!");</script>',
    [
        'html_input' => 'strip',
        'allow_unsafe_links' => false,
    ]
);
// Result: Inject: alert("Hello XSS!");

This method proves particularly valuable in user-generated content systems:

class ContentProcessor
{
    protected $secureOptions = [
        'html_input' => 'strip',
        'allow_unsafe_links' => false
    ];

    public function formatPost(string $content)
    {
        return Str::inlineMarkdown(
            $content, 
            $this->secureOptions
        );
    }

    public function processHashtags(string $content)
    {
        // Convert #hashtag to links while preserving markdown
        $processed = preg_replace(
            '/#(\w+)/',
            '[#$1](/tags/$1)',
            $content
        );

        return Str::inlineMarkdown(
            $processed,
            $this->secureOptions
        );
    }

    public function formatSystemMessage(string $template, array $variables)
    {
        $content = strtr($template, $variables);
        
        return Str::inlineMarkdown(
            $content,
            [
                'html_input' => 'escape',
                'allow_unsafe_links' => false
            ]
        );
    }
}

// Usage
$processor = new ContentProcessor();

$post = $processor->formatPost('**Breaking** news update!');
$hashtag = $processor->processHashtags('Love #Laravel development!');

The method excels in forum and discussion systems where rich formatting needs security:

class ForumPostService
{
    public function processReply(string $content, User $author)
    {
        // Handle code blocks and formatting
        $formatted = Str::inlineMarkdown($content, [
            'html_input' => 'strip',
            'allow_unsafe_links' => false,
            'use_autolinks' => true
        ]);
        
        return $this->addAuthorContext($formatted, $author);
    }
    
    public function formatQuote(string $originalContent, string $newContent)
    {
        $quote = "> " . str_replace("\n", "\n> ", $originalContent);
        $combined = $quote . "\n\n" . $newContent;
        
        return Str::inlineMarkdown($combined, [
            'html_input' => 'strip',
            'allow_unsafe_links' => false
        ]);
    }
    
    public function processCodeSnippet(string $content)
    {
        return Str::inlineMarkdown($content, [
            'html_input' => 'strip',
            'allow_unsafe_links' => false,
            'use_underline' => false // Prevent conflicts with code
        ]);
    }
}

For notification systems requiring formatted messages:

class NotificationFormatter
{
    public function formatActivityUpdate(Activity $activity)
    {
        $template = '**{user}** {action} in *{project}*';
        
        $message = strtr($template, [
            '{user}' => $activity->user->name,
            '{action}' => $activity->description,
            '{project}' => $activity->project->title
        ]);
        
        return Str::inlineMarkdown($message, [
            'html_input' => 'escape',
            'allow_unsafe_links' => false
        ]);
    }
    
    public function formatSystemAlert(string $message, array $context = [])
    {
        $processed = strtr($message, $context);
        
        return Str::inlineMarkdown($processed, [
            'html_input' => 'strip',
            'allow_unsafe_links' => false,
            'use_autolinks' => false // Disable for security
        ]);
    }
}

The inlineMarkdown method ensures secure Markdown processing by providing comprehensive XSS protection while maintaining the flexibility to format user content with common Markdown syntax like bold, italic, links, and code spans.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article