PHP : simple regex problem

2019-01-15 23:00发布

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条回答
男人必须洒脱
2楼-- · 2019-01-15 23:51

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

查看更多
登录 后发表回答