Методы замены \n на в PHP: подробное руководство

Метод 1: использование функции str_replace()

<?php
$text = "This is a sample text.\nIt has multiple lines.";
$html = str_replace("\n", "<br>", $text);
echo $html;
?>

Метод 2: использование функции nl2br()

<?php
$text = "This is a sample text.\nIt has multiple lines.";
$html = nl2br($text);
echo $html;
?>

Метод 3: использование функции preg_replace()

<?php
$text = "This is a sample text.\nIt has multiple lines.";
$html = preg_replace("/\r?\n/", "<br>", $text);
echo $html;
?>

Метод 4. Расчленение и объединение строки

<?php
$text = "This is a sample text.\nIt has multiple lines.";
$lines = explode("\n", $text);
$html = implode("<br>", $lines);
echo $html;
?>

Метод 5: использование функции strtr()

<?php
$text = "This is a sample text.\nIt has multiple lines.";
$replace = array("\n" => "<br>");
$html = strtr($text, $replace);
echo $html;
?>

Используя эти методы, вы можете гарантировать, что ваш текст будет правильно отформатирован с разрывами строк при отображении на веб-страницах.