删除任何第一个字符之前和任何最后一个字符之后的空格

Remove spaces in front of any first character and after any last character

我想 trim 所有 spaces 在前面的任何第一个字符(除了 space,可以是数字或一个字母字符)和任何最后一个字符之后。使用 /([A-Z ])\w+/,实际上效果很好,但我的 $output 却没有。我到底要怎么做才能得到'Any Word'?这应该适用于任何数量的单词,而不仅仅是 space 中的两个。

$text = '                   Any Word                ';

preg_match_all('/([A-Z ])\w+/', $text, $output);

var_dump($output);

感谢您的帮助!

trim(), it should work for you. Check the live demo.

您可以使用 trim 函数从字符串的开头和结尾删除任何 space:

$text = '                   Any Word                ';

$output = trim($text);

var_dump($output);

如果你真的想在这里使用正则表达式,你可以尝试匹配模式 \s+(.*)\s+:

$string = '                   Any Word                ';
preg_match('/\s+(.*)\s+/', $string, $m);
echo $m[1];

输出:

Any Word

不过,您也可以使用 trim()

Demo