字符串按模式拆分成行

时间:2011-05-17 05:38:58

标签: php split

我有一个这样的字符串:

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 个答案:

答案 0 :(得分: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 :(得分: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
)
*/

答案 2 :(得分:1)

尝试使用内置的preg_split()函数:http://php.net/manual/en/function.preg-split.php

答案 3 :(得分: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]}";
?>
相关问题