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?
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 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"
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;
}
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.
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);