baloonrocket baloonrocket - 9 days ago 5
PHP Question

Remove text using str_Replace

I have seven lines of text. I want to use PHP to do the things below.

First of all, I want to remove all the lines which don't have the word 'MARCO1998' in them.

Then, for the remaining lines, I want to remove everything except for the 1-3 numbers after the word 'MAP'

And then, after there's only seven rows of 1-3 numbers left, I want to remove the duplicates.

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

Answer
<?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;
}
Comments