使用str_Replace删除文本

时间:2016-11-25 16:31:20

标签: php html

我有七行文字。我想用PHP来做下面的事情。

首先,我想要删除所有没有单词' MARCO1998'在他们中间。

然后,对于其余的行,我想删除除之后的<1-3>数字之外的所有内容&#39; MAP&#39;

然后,在那里只剩下七行1-3个数字之后,我想删除重复数据。

17.10.16    11:32:39    MAP104  MARCO1998   zerstoert   NIGHTRIDER
17.10.16    14:17:25    MAP66   MARCO1998   zerstoert   SPARTACULS
17.10.16    14:26:15    MAP66   MARCO1998   zerstoert   SUPERONE
17.10.16    23:09:04    MAP104  MARCO1998   zerstoert   JOCKSTRAP7
18.10.16    14:27:45    MAP244  MARCO1998   zerstoert   MARIA07
18.10.16    19:50:37    MAP40   MARCO1998   zerstoert   LILIENKILL
19.10.16    07:08:41    MAP186  KOBOLD1 zerstoert   MARCO1998

1 个答案:

答案 0 :(得分:0)

<?php
// Input string with newlines
$str = "17.10.16    11:32:39    MAP104  MARCO1998   zerstoert   NIGHTRIDER
17.10.16    14:17:25    MAP66   MARCO1998   zerstoert   SPARTACULS
17.10.16    14:26:15    MAP66   MARCO1998   zerstoert   SUPERONE
17.10.16    23:09:04    MAP104  MARCO1998   zerstoert   JOCKSTRAP7
18.10.16    14:27:45    MAP244  MARCO1998   zerstoert   MARIA07
18.10.16    19:50:37    MAP40   MARCO1998   zerstoert   LILIENKILL
19.10.16    07:08:41    MAP186  KOBOLD1 zerstoert   MARCO1998";

// Split long string on newlines
$str_split = explode("\n", $str);
$values = [];

// Loop each line
foreach ($str_split as $v) {
    // If the line does not contain MARCO1998, we skip this line
    if (strpos($v, 'MARCO1998') === false) {
        continue;
    }

    // Use regex to capture MAP<integer>{1,3}
    preg_match_all('/MAP(?P<id>[0-9]{1,3})/', $v, $matches);

    // Make sure that the match returned a valid result
    if (isset($matches['id']) and isset($matches['id'][0]) and strlen($matches['id'][0]) > 0) {
        $values[] = $matches['id'][0];
    }
}

print_r($values); //  104, 66, 66, 104, 244, 40, 186

// If you only like to have the unique values
$values = array_unique($values);
print_r($values); // 104, 66, 244, 40, 186

// Output each ID
foreach ($values as $v) {
    echo $v;
}