Remove whitespace from string

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.

<?php
function replace_whitespace($Value = '')
{
	// Replace any whitespace with only a single space
	return preg_replace('/\s+/', ' ', trim($Value));
}
?>

Usage:

<?php
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
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • BlinkList
  • FriendFeed
  • LinkedIn
  • MySpace
  • Slashdot
  • StumbleUpon
  • Twitter
  • Yahoo! Bookmarks
  • Add to favorites
  • email

Comments are closed.

Switch to our mobile site