How to remove spaces before and after a string?

For completeness (as this question is tagged regex), here is a trim() reimplementation in regex:

function preg_trim($subject) {
    $regex = "/\s*(\.*)\s*/s";
    if (preg_match ($regex, $subject, $matches)) {
        $subject = $matches[1];
    }
    return $subject;
}
$words = '      my words     ';
$words = preg_trim($words);
var_dump($words);
// string(8) "my words"

You don't need regex for that, use trim():

$words = '      my words     ';
$words = trim($words);
var_dump($words);
// string(8) "my words"

This function returns a string with whitespace stripped from the beginning and end of str.


For some reason two solutions above didnt worked for me, so i came up with this solution.

function cleanSpaces($string) {
    while(substr($string, 0,1)==" ") 
    {
        $string = substr($string, 1);
        cleanSpaces($string);
    }
    while(substr($string, -1)==" ")
    {
        $string = substr($string, 0, -1);
        cleanSpaces($string);
    }
    return $string;
}

Tags:

Php

Regex