1
$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, " ");功能。它正在删除最后一个和第一个单词空格,但单词中间最终用户给出了两个或更多空格如何删除我们将在 php 中放入单个空格的那些空格。请帮助我的朋友。

对不起我的英语不好

4

9 回答 9

1

尝试这样的事情

<?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);
?>
于 2013-09-26T06:53:24.727 回答
0

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

于 2013-09-26T06:59:21.367 回答
0

您可以使用 str_replace 从字符串中删除所有空格。

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

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

于 2013-09-26T06:54:28.543 回答
0

修剪 + str_replace

echo trim(str_replace("  ", " ", $ss));
于 2013-09-26T07:15:41.193 回答
0

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

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

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;
}
于 2014-03-12T05:49:14.587 回答
0

使用 preg_replace():

  $string = 'First     Last';
  $string = preg_replace("/\s+/", " ", $string);
  echo $string;
于 2013-09-26T06:57:15.507 回答
0

您可以使用preg_replace一个替换多个空格。

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

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

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

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

$string = preg_replace("/(\s+| {2,})/", " ", $string)
于 2013-09-26T06:57:20.400 回答
0
<?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

于 2013-09-26T06:58:14.003 回答
0

您可以使用ltrimrtrim功能,例如

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

结果 kompetisi indonesia kompetisi indonesia

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

于 2016-12-10T14:01:18.757 回答