How to Replace \n with br in Laravel?

Posted by

Introduction

Have you ever encountered the need to replace newline characters (\n) with HTML line breaks (<br>) in your Laravel application? If so, you’re in the right place! In this blog post, we will explore a simple and effective way to achieve this using live examples.

Why is it important?

When dealing with user-generated content, such as comments or forum posts, it’s essential to properly format the text to ensure readability. By replacing newline characters with HTML line breaks, we can maintain the intended formatting and improve the user experience.

The Problem

Laravel, being a powerful PHP framework, provides various string manipulation functions. However, it doesn’t have a built-in method to replace newline characters with HTML line breaks. This can be frustrating when you’re working on a project that requires this functionality.

Example

Step 1:- Html code

<!DOCTYPE html>
<html>
<head>
    <title>Replace Newlines Example</title>
</head>
<body>
    <h1>Text with Newlines:</h1>
    <pre>{{ $textWithNewlines }}</pre>

    <h1>Text with Line Breaks:</h1>
    <p>{!! $textWithLineBreaks !!}</p>
</body>
</html>

Step 2:- web.php

Route::get('/',[UserController::class,'importView'])->name('import-view');

Step 3:- Controller

 public function importView()
    {
        $textWithNewlines = "This is line 1.\nThis is line 2.\nThis is line 3.";
        $textWithLineBreaks = nl2br($textWithNewlines);
    
        return view('importFile', compact('textWithLineBreaks','textWithNewlines'));
    }

Output:-

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x