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.
There are a few different ways to remove line breaks from a string in PHP. Here are two options:
- Use the
str_replacefunction:
How to remove line breaks from a string in PHP?
<?php
$string = "This is a string\nwith line breaks.";
$string = str_replace(["\r\n", "\r", "\n"], ' ', $string);
echo $string; // Outputs: "This is a string with line breaks."
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
- Use the preg_replace function with a regular expression that matches line breaks:
How to remove line breaks from a string in PHP with a regular expression?
<?php
$string = "This is a string\nwith line breaks.";
$string = preg_replace('/[\r\n]+/', ' ', $string);
echo $string; // Outputs: "This is a string with line breaks."Note that the regular expression /[\r\n]+/ matches both Windows-style (\r\n) and Unix-style (\n) line breaks. These examples replace line breaks with a space. To remove them entirely, replace ' ' with ''.