【问题标题】:Regex to get string after a keyword正则表达式在关键字后获取字符串
【发布时间】:2015-03-11 17:55:04
【问题描述】:

我需要在一个字符串中搜索一个字符串并得到它后面的部分(没有空格)。

示例:

This ABC-Code: 12 3 45
Another ABC-Code: 678 9

现在我正在搜索关键字ABC-Code:,我想获取之后的数字(删除空格),所以结果是:

12345
6789

我试图用 substr() 解决这个问题,但问题是,前面的字符是可变的。所以我想我必须使用正则表达式,像这样:

preg_match("#ABC-Code:(.*?)\n#", $line, $match);
trim($match); // + remove spaces in the middle of the result

【问题讨论】:

    标签: php regex


    【解决方案1】:

    你需要使用preg_replace_callback函数。

    $str = <<<EOT
    This ABC-Code: 12 3 45
    Another ABC-Code: 678 9
    EOT;
    echo preg_replace_callback('~.*\bABC-Code:(.*)~', function ($m)
            { 
                return str_replace(' ', '', $m[1]);
            }, $str);
    

    输出:

    12345
    6789
    

    【讨论】:

      【解决方案2】:

      你可以使用:

      preg_match('#ABC-Code: *([ \d]+)\b#', $line, $match);
      

      然后使用:

      $num = str_replace(' ', '', $match[1]);
      // 12345
      

      给你号码。

      【讨论】:

        【解决方案3】:

        您仍然可以使用 substr 执行此操作:

        $string = 'This ABC-Code: 12 3 45';
        $search = 'ABC-Code:';
        $result = str_replace(' ', '', substr($string, strpos($string, $search) + strlen($search)));
        

        但其他答案中的正则表达式肯定更漂亮:)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-04
          • 1970-01-01
          • 2013-03-12
          • 1970-01-01
          • 1970-01-01
          • 2020-05-13
          • 2013-07-31
          • 1970-01-01
          相关资源
          最近更新 更多