0

Some of my HTML files contains string like :

{foreach $any_kind_of_charaters}
Any kind of string including "\n\r" and spaces here
{/foreach}

I want to apply PHP's preg_match_all on them and wanna return a nice array like printed below

Array
(
    [0] => {foreach $any_kind_of_charaters}
            Any kind of string including "\n\r" and spaces here
           {/foreach}
    [1] => any_kind_of_charaters
    [2] => Any kind of string including "\n\r" and spaces here
)

This REGEX : /\{foreach\s+\$(.*)\}\s+(.*)\s+\{\/foreach\}/ working okay for me,
but it fails when i add new lines(\n) between {foreach}{/foreach} tags.

You help will be much appreciated, thanks.

ARRAY AFTER USING "S" MODIFIER

Array
(
    [0] => {foreach $any_kind_of_charaters}
        Any kind of string including "\n\r" and spaces here
        {/foreach}
    [1] => any_kind_of_charaters}
        Any kind of string including "\n\r" and spaces here
    [2] => 
)

Look second key of the array contain unnecessary data, and last key of array is totally empty.

1 Answer 1

6

Set the s modifier flag on your regular expression.

http://php.net/manual/en/reference.pcre.pattern.modifiers.php


Like this: /\{foreach\s+\$(.*)\}\s+(.*)\s+\{\/foreach\}/s <- note the modifier

Sign up to request clarification or add additional context in comments.

2 Comments

try removing the \s since now a dot will match that too. Also try the m modifier.
no luck with m modifier, and the array become more ugly after replacing \s to .

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.