Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdullahbutt/872e982049048d980ac89e7d1107c614 to your computer and use it in GitHub Desktop.
Save abdullahbutt/872e982049048d980ac89e7d1107c614 to your computer and use it in GitHub Desktop.
Remove Whitespace and line breaks from String using PHP
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