Home  >  Article  >  Backend Development  >  Introduction to PHP regular parsing multiple loop templates

Introduction to PHP regular parsing multiple loop templates

不言
不言Original
2018-06-29 10:12:191696browse

这篇文章主要介绍了PHP正则解析多重循环模板,结合实例形式分析了php基于正则的循环遍历与解析相关操作技巧,需要的朋友可以参考下

本文实例讲述了PHP正则解析多重循环模板。分享给大家供大家参考,具体如下:

$str = "客户您好,为您推荐以下项目:(crm{项目2:项目名称} (crm{项目3:项目名称}crm)  crm)以及(crm{项目1:项目名称}crm)";
$start = '(crm'; //循环开始标记
$end  = 'crm)'; //循环结束标记   
//循环标记,需要转移的符号,前面需要加入转义符 '\'
$need_escape = array('^', '$', '(', ')', '.', '[', ']', '|', '*', '?', '+', '/', '{', '}');
foreach($need_escape as $val)
{
   if(strpos($start, $val) !== FALSE)//存在需要转义的符号
   { 
     $escape = '\\'.$val;
     $start = str_replace($val, $escape, $start);
   }
   if(strpos($end, $val) !== FALSE)//存在需要转义的符号
   { 
     $escape = '\\'.$val;
     $end = str_replace($val, $escape, $end);
   }
}
/*----------------------------------
* 正则解析出【没有子循环】的【循环】
* 【没有子循环】:不包含循环开始标记
* 【循环】:被循环标记包含(开始标记、结束标记)
* ---------------------------------*/
//$pattern = '/\(crm((?!\(crm).)+crm\)/U';
$pattern = '/'.$start.'((?!'.$start.').)+'.$end.'/U';
preg_match_all($pattern, $str, $matches);
echo "<pre class="brush:php;toolbar:false">";
print_r($matches);
echo "
";

运行结果:

Array
(
    [0] => Array
        (
            [0] => (crm{项目3:项目名称}crm)
            [1] => (crm{项目1:项目名称}crm)
        )
    [1] => Array
        (
            [0] => }
            [1] => }
        )
)

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

php 判断IP为有效IP地址的方法php实例

PHP实现的防止跨站和xss攻击代码php技巧

基于PHP实现的多元线性回归模拟曲线算法php技巧

The above is the detailed content of Introduction to PHP regular parsing multiple loop templates. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn