2011-05-17 39 views
2

我有一個字符串是這樣的:字符串分割成線的PHP通過模式

1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps 

我想將字符串分割成兩個字符串是這樣的:

192.168.122.1 0.89 Bps 
192.168.122.10 0.25 Bps 
+4

所以你的研究說?你失敗了嗎?你試過什麼了? – 2011-05-17 05:40:50

+0

我試過爆炸,拆分,分裂所有的東西仍然無法找到方式感謝您的評論 – 2011-05-17 05:42:20

回答

2

preg_split例如:

$str = "1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps"; 

$split = preg_split("~\s?\d\.\s~", $str, -1, PREG_SPLIT_NO_EMPTY); 

/* 
Array 
(
    [0] => 192.168.122.1 0.89 Bps 
    [1] => 192.168.122.10 0.25 Bps 
) 
*/ 
+0

完美的謝謝smott – 2011-05-17 07:26:42

+0

如果你的'\ d'中有超過9個項目,你可能需要添加'+'量詞。 – alex 2011-05-17 23:11:48

4

你可以使用正則表達式。 \d[0-9]字符類的快捷方式,常用於以下表達式中。

preg_match_all('/\d+\. \d+\.\d+\.\d+\.\d+ [\d.]+ Bps/', $str, $matches); 

CodePad

在你的榜樣,$matches將包含...

array(1) { 
    [0]=> 
    array(2) { 
    [0]=> 
    string(25) "1. 192.168.122.1 0.89 Bps" 
    [1]=> 
    string(26) "2. 192.168.122.10 0.25 Bps" 
    } 
} 
1

他們是永遠保證按照這個順序?什麼是靜態的,什麼變化等等?這裏

實在不夠標準,但你可能會看着爆炸的空間,從那裏......

<?php 
$str = "1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps"; 
$arr = explode(" ", $str); 
$your_result = "{$str[1]} {$str[3]} {$str[4]}\n{$str[6]} {$str[7]} {$str[8]}"; 
?>