如何删除字符串前后的空格?

时间:2021-04-05 20:24:32

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?

如何删除之前和之后的空格?

3 个解决方案

#1


47  

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

你不需要正则表达式,使用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.

此函数返回一个字符串,其中从str的开头和结尾剥去了空格。

#2


5  

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

为了完整性(因为这个问题被标记为正则表达式),这里是正则表达式中的trim()重新实现:

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"

#3


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


47  

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

你不需要正则表达式,使用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.

此函数返回一个字符串,其中从str的开头和结尾剥去了空格。

#2


5  

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

为了完整性(因为这个问题被标记为正则表达式),这里是正则表达式中的trim()重新实现:

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"

#3


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;
}