duanjiangzhi6851 2016-11-25 16:31
浏览 60
已采纳

使用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
  • 写回答

1条回答 默认 最新

  • dongzhao5970 2016-11-25 16:42
    关注
    <?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("
    ", $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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决