Remove whitespace from string
May 23, 2010 PHP Coding
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. I am sure I could use trim(), ltrim() or rtrim() to remove the spaces but that does not remove the multiple spaces between names. 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 = 'Daniel Kassner'; echo $Text,' - ',strlen($Text),'<br />'; $Text = ReplaceWhitespace($Text); echo $Text,' - ',strlen($Text); echo '</pre>';
Output:
Daniel Kassner - 18 Daniel Kassner - 14
