PHP:简单的正则表达式问题 [英] PHP : simple regex problem

查看:91
本文介绍了PHP:简单的正则表达式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一些HTML文件包含如下字符串:

Some of my HTML files contains string like :

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

我想在它们上应用PHP's preg_match_all并想返回一个漂亮的array,如下面的

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
)

此REGEX:/\{foreach\s+\$(.*)\}\s+(.*)\s+\{\/foreach\}/对我来说还可以,
但是当我在{foreach}{/foreach}标记之间添加新行(\ n)时失败.

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

非常感谢您的帮助.

使用"S"修饰符后的数组

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] => 
)

查找arraysecond key中包含不必要的数据,而arraylast key完全为空.

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

推荐答案

在正则表达式上设置s修饰符标志.

Set the s modifier flag on your regular expression.

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

像这样:/\{foreach\s+\$(.*)\}\s+(.*)\s+\{\/foreach\}/s<-注意修饰符

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

这篇关于PHP:简单的正则表达式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆