PHP : simple regex problem

我们两清 提交于 2019-11-26 23:43:03

问题


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:


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



来源:https://stackoverflow.com/questions/7385273/php-simple-regex-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!