Search code examples
phpregexpreg-match

preg_match between newlines and beginning or ending


I have a number of lines in my value where I need to run preg_match between newlines, returns and beginning or end.

$text = "
ENG CHG NOTE
2A
LTR CHK
AH 2000
YE
NOTE 2
";

for example:

preg_match("/((?P<value>\\d+(.\\d+)*?)\s?(?P<unit>YE))/"

I want to make sure that preg_match is only looking for digits and YE in the above example. In this example 2000, which belongs to AH, would show a false value for YE. How can I include \r\n and beginning or end, surrounding my current regex?


Solution

  • In this example 2000, which belongs to AH, would show a false value for YE. How can I include \r\n and beginning or end, surrounding my current regex?

    In the example you have, the number comes right after a YE followed with a newline. Since \s matches a newline symbol, too, you need to adjust the pattern to match only horizontal spaces.

    There are two patterns you may leverage here: \h or [^\S\r\n].

    '~(?P<value>\d+(?:.\d+)*?)\h?(?P<unit>YE)~'
                              ^^
    

    See this regex demo. PHP demo:

    $re = '~(?P<value>\d+(?:.\d+)*?)\h?(?P<unit>YE)~'; 
    $str = "ENG CHG NOTE\n2A\nLTR CHK\nAH 2000\nYE\nNOTE 2\n3444 YE\n"; 
    preg_match_all($re, $str, $matches);
    print_r($matches);