How to remove spaces before and after a string?

自作多情 提交于 2021-02-07 04:43:05

问题


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?


回答1:


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.




回答2:


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"



回答3:


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



回答4:


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.




回答5:


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


来源:https://stackoverflow.com/questions/12758259/how-to-remove-spaces-before-and-after-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!