如何在 PHP 中删除两个空格以及第一个和最后一个空格


how to remove two white spaces and first and last white spaces in php

$s = "  xyxz  ";
echo trim($s, " "); //out put:xyz
$ss = " xyz  pqrs" ;

echo trim($ss, " "); //out put:xyz  pqrs 
// i want out put:xyz pqrs

嗨,朋友们,我最近得到了trim($search_string, " ");函数.it正在删除最后一个和第一个单词空格,但单词中间最终用户给出了两个空格或多个空格,如何删除我们将放入php中单个空格的那些空格,请帮助我的朋友。

对不起,我的英语不好

试试这样的事情

<?php
$str="Hello World";
echo str_replace(" ","",$str);//HelloWorld

编辑:

然后部署Regular Expression

<?php
$str="   Hello      World I am  testing this          example   ";//Hello World I am testing this example
echo preg_replace('/'s's+/', ' ', $str);
?>
您可以使用str_replace从

字符串中删除所有空格。

http://php.net/manual/en/function.str-replace.php

str_replace(" ", "

, "字符串");这将用一个空格替换两个空格。

使用 preg_replace():

  $string = 'First     Last';
  $string = preg_replace("/'s+/", " ", $string);
  echo $string;
您可以使用

preg_replace将多个空格替换为一个空格。

$string = preg_replace("/ {2,}/", " ", $string)

如果要替换两个以上组中的任何空格,请使用

$string = preg_replace("/'s{2,}/", " ", $string)

或者,如果您还想用可以使用的空格替换空格以外的任何空格

$string = preg_replace("/('s+| {2,})/", " ", $string)
<?php
$str = 'foo   o';
$str = preg_replace('/'s's+/', ' ', $str);
// This will be 'foo o' now
echo $str;

http://www.php.net/manual/en/function.preg-replace.php

您可以使用preg_replace("/'s{2,}/"," ",$string)

修剪+str_replace

echo trim(str_replace("  ", " ", $ss));

您可以使用爆炸和内爆从中间以及第一个和最后一个空格中删除多个空格。

使用以下函数来简单返回修剪的字符串。

function removeSpaces( $string )
{
    // split string by space into array
    string_in_array = explode(" ", $string_filter );
    // concatenate array into string excluding empty array as well as spaces
    $string_with_only_one_space = implode(' ', array_filter( $string_in_array ));
    return $string_with_only_one_space;
}
您可以使用

ltrimrtrim函数,例如

$text = ' kompetisi indonesia ';
echo $text.'<br/>';
$text = ltrim(rtrim($text));
echo $text;

结果 印度尼西亚孔佩蒂西印度尼西亚孔佩蒂西

参考 : http://php.net/manual/en/function.ltrim.php 和 http://php.net/manual/en/function.rtrim.php