PHP regular expression for multi-line search

I use preg_ * in PHP to search for a template <!-- %{data=THIS GETS MATCHED}% -->and pull out the consistent text.

Template for this:

preg_match('#<!-- %{' . $knownString . '\s*=\s*(.*?)}% -->#', ...)

I would like it to search across multiple rows for a row. For instance:

<!-- %{data=
THIS GETS
MATCHED AND
RETURNED
}% -->

How can I change the current template for this search feature?

+3
source share
3 answers

You must add the "s" template modifier , without it, the dot matches any character except for a new line:

preg_match('#<!-- %{' . $knownString . '\s*=\s*(.*?)}% -->#s', ...)
+6
source

Does it work preg_match('#<!-- %{' . $knownString . '\s*=\s*(.*?)}% -->#s', ...)?

I don't have PHP here atm work, so I can not test it ...

+1

:

<?php
    $testString = "<!-- %{data=
THIS GETS
MATCHED AND
RETURNED
}% -->";
    $knownString = "data";
    preg_match( "@<!-- %\\{" . $knownString . "\\s*=\\s*([^\\}]+)\\}% -->@", $testString, $match );
    var_dump( $match );
?>

:

array(2) {
  [0]=>
  string(54) "<!-- %{data=
THIS GETS
MATCHED AND
RETURNED
}% -->"
  [1]=>
  string(34) "THIS GETS
MATCHED AND
RETURNED
"
}
+1

Source: https://habr.com/ru/post/1746319/


All Articles