How to remove line breaks from the string in PHP?

The line break can be removed from string by using str_replace() function. The str_replace() function is an inbuilt function in PHP which is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.

Syntax:

str_replace ( $searchVal, $replaceVal, $subjectVal, $count )



Return Type: This function returns a new string or array based on the $subjectVal parameter with replaced values.

Example: After replacing the <br> tag, the new string is taken in the variable text.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declare a variable and initialize it
// with strings containg <br> tag
$text = "Geeks<br>For<br>Geeks";
  
// Display the string
echo $text;
echo "\n";
  
// Use str_replace() function to
// remove <br> tag 
$text = str_replace("<br>", "", $text);
  
// Display the new string 
echo $text;
  
?>

chevron_right


Output:

Geeks
For
Geeks GeeksForGeeks

Using preg_replace() function: The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.

Syntax:

preg_replace( $pattern, $replacement, $subject, $limit, $count )

Return Value: This function returns an array if the subject parameter is an array, or a string otherwise.

Example: This example use preg_replace() function to remove line break.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declare a variable and initialize it
// with strings containg <br> tag
$text = "Geeks<br>For<br>Geeks";
  
// Display the string
echo $text;
echo "\n";
  
// Use preg_replace() function to
// remove <br> and \n
$text = preg_replace( "/<br>|\n/", "", $text );
  
// Display the new string 
echo $text;
  
?>

chevron_right


Output:

Geeks
For
Geeks GeeksForGeeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.