Remove whitespace from string
By: Daniel
I have been doing a lot of coding using the framework CodeIgniter lately so I have been creating many simple helper functions to perform different tasks. My most recent project involves creating PDF files with text from a database. The problem is that the text from the database is dirty, meaning that in a person’s name there could be multiple spaces between the person’s first and last name or even spaces at the end of their name. In dealing with legacy data that you cannot change but needs to be output correctly without those spaces you get creative. The below function should help solve this issue.
function replace_whitespace($Value = '') { // Replace any whitespace with only a single space return preg_replace('/\s+/', ' ', trim($Value)); }
Usage:
echo '<pre>'; $Text = 'White Lake Scripting'; echo $Text,' - ',strlen($Text),'<br />'; $Text = ReplaceWhitespace($Text); echo $Text,' - ',strlen($Text); echo '</pre>';
Output:
White Lake Scripting - 22 White Lake Scripting - 20




















