:::: MENU ::::
Posts tagged with: preg_replace

PHP: trim spaces in the middle of a string

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)

Continue Reading