Search code examples
regexpreg-matchpreg-match-all

preg_match() returning always empty arrays


I am still newbie so maybe it is simple but, I tried lot of things i found here and still cant get it right.

$patternPopis ='/(?:[^:|\d ])[A-Za-zÀ-ȕ .?+\d]+(?=\n)/i';

preg_match($patternPopis, $row, $popis);

in regexr its working nicely test strings ($rows) :

po 19. duben 2021 21:29 Objednávka vytvořena + ?\n //wanna this

st 21. duben 2021 10:27 name name: Objednávka automaticky označena jako dohledaná + ?\n //wanna this

st 21. duben 2021 17:18 name: Objednávka podána u GLS pod číslem 1004032\n //wanna this

i tried too preg_match_all() mb_eregi() tried to change regex with lookaheads

dump($popis); returning []

thx if you can help <3


Solution

  • If your \n is a newline, line feed \xA0 char, you can use

    <?php
    
    $patternPopis ='/[^:|\d ][A-Za-zÀ-ȕ .?+\d]+$/ium';
    $row = "po 19. duben 2021 21:29 Objednávka vytvořena + ?\n";
    if (preg_match($patternPopis, $row, $popis)){
        echo $popis[0];
    }
    

    See the PHP demo.

    Notes

    • (?:[^:|\d ]) = [^:|\d ], the non-capturing group is superfluous
    • The u flag is required as the text contains non-ASCII chars
    • m flag is advisable since you might want to find matches in a multiline text and the pattern suggested contains $ (instead of (?=\n))
    • $ with m flag matches a line end position, which makes the pattern leaner.

    If the \n is a two char combination, a backslash + n, you can use

    $patternPopis ='/[^:|\d ][A-Za-zÀ-ȕ .?+\d]+(?=\\\\n)/iu';
    $row = 'po 19. duben 2021 21:29 Objednávka vytvořena + ?\n';
    if (preg_match($patternPopis, $row, $popis)){
        echo $popis[0];
    }
    

    See this PHP demo.

    The (?=\\\\n) lookahead matches a location immediately followed with \ and then n chars. m flag is not necessary here.