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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12758259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:10:32  来源:igfitidea点击:

How to remove spaces before and after a string?

phpregex

提问by tarek

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?

怎么去掉前后的空格?

回答by Mihai Iorga

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 的开头和结尾去除了空格。

回答by Kaii

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

为了完整性(因为这个问题被标记为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"

回答by Alexandar Lazovic

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

回答by Rick

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) //gremove repeatedly. this same concept works in 'ed' (vi/vim)

也就是说^在开头\s+(空格)|\s+$(结尾的空格)//g重复删除。同样的概念适用于 'ed' (vi/vim)

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

有时最好只是回答提出的问题。