How to remove line breaks (no characters!) from the string?

There are a few different ways to remove line breaks from a string in PHP. Here are two options:

  1. Use the str_replace function:
<?php

$string = "This is a string\nwith line breaks.";
$string = str_replace(["\r\n", "\r", "\n", "\t"], ' ', $string);
echo $string; // Outputs: "This is a string with line breaks."

Watch a course Learn object oriented PHP

  1. Use the preg_replace function with a regular expression that matches line breaks:
<?php

$string = "This is a string\nwith line breaks.";
$string = preg_replace('/\s+/', ' ', $string);
echo $string; // Outputs: "This is a string with line breaks."

Note that the regular expression "/[\r\n]/" will match both Windows-style line breaks ("\r\n") and Unix-style line breaks ("\n").