我想删除字符串中的额外空格.我已经试过trim,ltrim,rtrim和其他人,但他们的工作是,甚至不尝试下面的东西.
//This removes all the spaces even the space between the words
// which i want to be kept
$new_string = preg_replace('/\s/u', '', $old_string);
Run Code Online (Sandbox Code Playgroud)
这有什么解决方案吗?
更新:-
输入字符串: -
"
Hello Welcome
to India "
Run Code Online (Sandbox Code Playgroud)
输出字符串: -
"Hello Welcome to India"
Run Code Online (Sandbox Code Playgroud)
rm *_*-rf 28
$cleanStr = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $str)));
Run Code Online (Sandbox Code Playgroud)
好的,所以你想修剪 字符串末尾的所有空格和 单词之间多余的空格.
您可以使用单个正则表达式执行此操作:
$result = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $subject);
Run Code Online (Sandbox Code Playgroud)
说明:
^\s+ # Match whitespace at the start of the string
| # or
\s+$ # Match whitespace at the end of the string
| # or
\s+(?=\s) # Match whitespace if followed by another whitespace character
Run Code Online (Sandbox Code Playgroud)
像这样(Python中的例子,因为我不使用PHP):
>>> re.sub(r"^\s+|\s+$|\s+(?=\s)", "", " Hello\n and welcome to India ")
'Hello and welcome to India'
Run Code Online (Sandbox Code Playgroud)
如果要删除字符串中的多个空格,可以使用以下命令:
$testStr = " Hello Welcome
to India ";
$ro = trim(preg_replace('/\s+/', ' ', $testStr));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14933 次 |
| 最近记录: |