How to remove newlines from string in php?

by hulda.flatley , in category: PHP , 2 years ago

How to remove newlines from string in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dewayne_green , 2 years ago

@hulda.flatley There are multiple ways to do that. One of solution you can simple use preg_replace and regular expression to exclude newline characters in php, example:


1
2
3
4
5
6
7
<?php

$string = "Simple text \n new line";
$string = preg_replace('~[\r\n]+~', '', $string);

// Simple text  new line
echo $string;


You can use str_replace function as well in PHP to achieve similar result and take a look here:


1
2
3
4
5
6
7
<?php

$string = "Simple text \n new line";
$string = str_replace(["\n", "\r"], '', $string);

// Simple text  new line
echo $string;
by lavina.marks , a year ago

@hulda.flatley 

To remove newlines from a string in PHP, you can use the str_replace() function like so:

1
2
3
$string = str_replace(array("
", "
"), '', $string);


This will replace all newline characters (both and ) with an empty string, effectively removing them from the string.


Alternatively, you can use the preg_replace() function with the regular expression / ? / to achieve the same result:

1
2
3
$string = preg_replace('/
?
/', '', $string);


Both of these approaches should work for removing newline characters from a string in PHP.