2013-09-26 62 views
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中放入單個空間。請幫助我的朋友。如何刪除兩個空格和第一個和最後的空格在PHP

抱歉我的英文不好

+2

你能提供一個例子嗎?並請在嘗試之前嘗試測試一些內容! –

回答

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); 
?> 
+0

hello bass我只想刪除雙空白或更多空白到單個空白空間。你明白我在說什麼 – user2798006

+0

@ user2798006,檢查更新後的答案。 –

0

使用的preg_replace():

$string = 'First  Last'; 
    $string = preg_replace("/\s+/", " ", $string); 
    echo $string; 
0

您可以使用preg_replace與來替代多個空格。

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

如果要替換任何空格中的兩個以上使用

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

或者,如果你要同時更換比用空格空格之外的任何空格組可以使用

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

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

0

裝飾+ str_replace函數

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

您可以使用爆炸和內爆從中間以及第一和最後一個空格刪除多個空格。

使用以下函數可以簡單地返回修剪過的字符串。

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; 
} 
相關問題