When you let users input text in a textfield or input box it is always a good idea to use trim function to remove spaces form the beginning or the end of the string.
Today I needed a function to trim spaces from the middle of a string and replace with a single space.
/*
this will return the string where groups of consecutive spaces
are collapsed in a single space
eg. $str = "This is my test string";
function will output "This is my test string"
*/
function centerTrim($str){
return preg_replace("/\s+/", " ", $str)
}
if you need to remove all spaces you can use this function:
/*
eg. $str = "This is my test string";
function will output "Thisismyteststring"
*/
function centerTrim2($str){
return preg_replace("/\s+/", "", $str)
}