35

I have two words spirited by space of course, and a lot of spaces before and after, what I need to do is to remove the before and after spaces without the in between once.

How can I remove the spaces before and after it?

5 Answers 5

97

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.

2
  • How come this didn't work for me ? I still see my white spaces after the strings. Any hints ? Anyone ?
    – code-8
    Feb 24, 2016 at 13:57
  • 1
    Maybe they are not really whitespaces. I encountered this problem with texts from Office Word. Mar 5, 2016 at 6:43
6

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"
1
  • I needed to trim a simple space from the beginning and end of a string (I somehow skipped over the top voted answer here to use PHP's built in trim function). Prior to that, I used your function. It was returning an empty string. This function only works if there is more than one space at the beginning and end of a string. Not a terrible idea to have a function like this that strips out all spaces, but it needs to work with just one space, too.
    – Edward B.
    Dec 10, 2020 at 15:44
1

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;
}
1
  • 1
    Be aware that while this may work, the overhead for the recursion makes this extremely slow and inefficient. I am not sure why trim didn't work for you as it should work fine on any string. Nov 19, 2015 at 21:39
0

The question was about how to do it with regex, so:

$str1=~ s/^\s+|\s+$//g; 

That says ^ at the begining \s+ (white space) | or \s+$ (whitespace at the end) //g remove repeatedly. this same concept works in 'ed' (vi/vim)

sometimes it is better just to answer the question that was asked.

-1

If trim is not working for you as well , try this. You just need to write it to a different variable;

$str = ' hello world ';
echo strlen($str);

$trim_str = trim($str);
echo strlen($trim_str);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.