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?
strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.
strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
trim() method removes the leading and trailing spaces present in the string.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With