Search code examples
phpregexpreg-match

preg match only one line in each match


I have this pattern.. The matches must not cross multiple lines (there must not be any newline char in the matches) so I added the m modifier..

But sometimes there is a \n in the matches.. How to prevent this?

preg_match_all('/(?<!\d|\d\D)(?:dk)?([\d\PL]{8,})/m', $input, $matches, PREG_PATTERN_ORDER);

Solution

  • The \PL pattern matches any char but a Unicode letter and also matches digits and whitespace chars. So, [\d\PL] can be shortened to \PL and since you need to subtract line breaks from it, replace it with the reverse shorthand character class (\pL) and use it inside a negated bracket expression, [^\pL], and add \r and \n there:

    '/(?<!\d|\d\D)(?:dk)?([^\pL\r\n]{8,})/u'
    

    The m modifier is redundant since it only redefines the behavior of ^ and $ anchors. You might need the u modifier though, for the Unicode property class to work safely with Unicode strings in PHP/PCRE. Change \d to [0-9] and \D to [^0-9] if you only want to match ASCII digits.