2012-04-17 37 views
0

我希望將文本字符串拆分爲空格分隔的單詞。 我用php explode()函數問題 - 空格

$words=explode(" ", $text); 

不幸的是,這種方法並不能很好地爲我工作,因爲我想知道有多少空間之間都英寸

有沒有什麼更好的方法來做到這一點不是通過整個$文字,符號的符號去,用while語句來填寫$用整數位($spaces=array();)(空格數量,在大多數情況下,1)和用符號將文本讀入$ words = array()符號?

這裏是一個額外的解釋。

$text="Hello_world_____123"; //symbol "_" actually means a space 

需要:

$words=("Hello","world","123"); 
$spaces=(1,5); 
+0

正則表達式是你的朋友。 :) – 2012-04-17 18:22:09

+0

嗯... substr_count會給我6上面的例子。 preg_split分割(任意數量)將字符串分成3個字。我如何知道6 = 5 + 1,但不是3 + 3? – Haradzieniec 2012-04-17 18:34:50

回答

1

有很多方法可以做到你想要做什麼,但我可能會選擇preg_split()array_map()組合:

$text = 'Hello world  123'; 
$words = preg_split('/\s+/', $text, NULL, PREG_SPLIT_NO_EMPTY); 
$spaces = array_map(function ($sp) { 
    return strlen($sp); 
}, preg_split('/\S+/', $text, NULL, PREG_SPLIT_NO_EMPTY)); 

var_dump($words, $spaces); 

輸出:

array(3) { 
    [0]=> 
    string(5) "Hello" 
    [1]=> 
    string(5) "world" 
    [2]=> 
    string(3) "123" 
} 
array(2) { 
    [0]=> 
    int(1) 
    [1]=> 
    int(5) 
} 
+0

這是優雅,緊湊,我相信它速度快(比我猜想的更快)。有用。謝謝。 – Haradzieniec 2012-04-17 18:44:41

2

使用正則表達式來代替:

$words = preg_split('/\s+/', $text) 

編輯

$spaces = array(); 
$results = preg_split('/[^\s]+/', $text); 
foreach ($results as $result) { 
    if (strlen($result) > 0) { 
    $spaces [] = strlen($result); 
    } 
} 
+0

他只需要空間的數量。 – Ozzy 2012-04-17 18:24:20

+0

這是如何回答OP的問題? – webbiedave 2012-04-17 18:26:05

+0

我被'我希望將文本字符串拆分爲空格分隔的單詞' – Tchoupi 2012-04-17 18:26:42

0

你仍然可以得到的空格數我n between like:

$words = explode(" ", $text); 
$spaces = sizeof($words)-1; 

這不適合你嗎?

+0

謝謝,但並不是說每對單詞之間有多少空格甚至沒有說空間的總數。 – Haradzieniec 2012-04-17 18:24:42

+0

@Haradzieniec我以爲你想分離每個單詞?什麼詞有他們的空間? :/空格的數量是$ spaces'(數組中的字數 - 1)' – Ozzy 2012-04-17 18:26:35

+0

我給一個問題解釋了一個例子。謝謝。 – Haradzieniec 2012-04-17 18:28:50