Search code examples
phpregexpreg-matchline-breaksmultiline

preg_match with multiline doesn't work correctly


I have the following code :

$data = "numbers{One
Two
Three}";

preg_match("~(?<=numbers{)(.*?)(?=})~", $data, $result);
echo $result[0];

The preg_match doesn't work i don't know why if the data is just one line then it works


Solution

  • The . doesn't match a newline use the s modifier:

    ~(?<=numbers{)(.*?)(?=})~s
    

    Or you could just match on NOT }:

    ~(?<=numbers{)([^}]*)(?=})~
    

    Not knowing all of you requirements, you may be able to simplify it:

    preg_match("~numbers{([^}]*)}~", $data, $result);
    echo $result[1];