Search code examples
phpregexvalidationpattern-matching

PHP regex starting and ending with < and > produces an unknown modifier warning


I got a bunch of XML files that contain an ID. e.g.

<WINE_PRODUCER>9456</WINE_PRODUCER>

I need to check, e.g. which file contains a WINE_PRODUCER id=9456:

$content = file_get_contents("my.xml");
$Num = 9456;
$pattern = "<WINE_PRODUCER>$Num<\/WINE_PRODUCER>";
$res = preg_match("$pattern", $content);

I got error PHP Warning: preg_match(): Unknown modifier '9'

basically it does not like numbers in the pattern.

What do I do? googled a lot but all lead to matching a group of numbers...

PS: I do not want to use DOM xml parser in this case due to performance.


Solution

  • If you always need to match a fixed number you can just do a strstr.

    $num = 9456;
    $find = "<WINE_PRODUCER>". $num . "</WINE_PRODUCER>";
    $found = strstr($content, $find) !== false;
    

    To fix your regular expression, you need to specify delimiters:

    $pattern = "@<WINE_PRODUCER>$Num<\/WINE_PRODUCER>@";
    

    should work, but you probably don't need a regexp.