3

I'm using preg_* in PHP to search for the pattern <!-- %{data=THIS GETS MATCHED}% --> and pull out the matched text.

The pattern for this is:

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

What I would like it to do is search across multiple lines for the string. For example:

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

How can I edit my current pattern to have this search ability?

3 Answers 3

6

You should add "s" pattern modifier, without it dot matches any character except for newline:

preg_match('#<!-- %{' . $knownString . '\s*=\s*(.*?)}% -->#s', ...)
Sign up to request clarification or add additional context in comments.

1 Comment

I'd secure $knownString with preg_quote() before gluing it to the rest of the regexp.
1

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

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

1 Comment

I managed to get it working by using /<!-- %{' . $knownString . '=\s*(.*?)}% -->/s. I'm terrible at regex, however, so if you're looking at that thinking "...lol?". Please tell me xD
1

This seems to work:

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

Returned:

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

1 Comment

m, or multiline mode, changes the meaning of the ^ and $ anchors, enabling them to match at line boundaries as well as at the beginning and end of the string. Your regex works because you changed the dot to ([^\\}]; the m is irrelevant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.