Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove spaces before and after a string?

Tags:

regex

php

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?

like image 868
tarek Avatar asked Oct 06 '12 08:10

tarek


People also ask

How do you remove spaces after a string?

strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.

How do you remove spaces before and after a string in python?

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.

Which method is used to remove whitespace from both ends of a string?

trim() method removes the leading and trailing spaces present in the string.


2 Answers

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.

like image 107
Mihai Iorga Avatar answered Oct 10 '22 13:10

Mihai Iorga


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" 
like image 24
Kaii Avatar answered Oct 10 '22 14:10

Kaii