How to remove line breaks from the string in PHP?
Last Updated :
01 Apr, 2021
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.
php
<?php
$text = "Geeks<br>For<br>Geeks" ;
echo $text ;
echo "\n" ;
$text = str_replace ( "<br>" , "" , $text );
echo $text ;
?>
|
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.
php
<?php
$text = "Geeks<br>For<br>Geeks" ;
echo $text ;
echo "\n" ;
$text = preg_replace( "/<br>|\n/" , "" , $text );
echo $text ;
?>
|
Output:
Geeks
For
Geeks
GeeksForGeeks
Share your thoughts in the comments
Please Login to comment...