Created
March 12, 2019 13:15
-
-
Save abdullahbutt/872e982049048d980ac89e7d1107c614 to your computer and use it in GitHub Desktop.
Remove Whitespace and line breaks from String using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://arjunphp.com/remove-whitespace-line-breaks-string-php/ | |
Remove Whitespace and line breaks from String using PHP | |
In PHP we have in-build functions to replace white-space from the start and end of the string these are trim, ltrim and rtrim. These functions are incapable of removing line breaks from the target string, a simple search and replace will not get line breaks. | |
trim() function will remove white-space from start and end of the given string. | |
rtrim() function will remove white-space from end of the given string. | |
ltrim() function will remove white-space from the begging of the string. | |
You can use preg_replace() function to find all instances of any white-space/line breaks and remove them from the string. | |
Here is an example code snippet of how you can use the preg_replace() function to remove all the white-space and line breaks from a string. | |
<?php | |
$pattern = '/\s*/m'; | |
$replace = ''; | |
$message= ' PHP rocks '; | |
$removedLinebaksAndWhitespace = preg_replace( $pattern, $replace,$message); | |
echo $removedLinebaksAndWhitespace ; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment