PHP在多个自定义标记之间获取文本
我需要解析一个自定义模板文件 假设我的模板文件如下所示PHP在多个自定义标记之间获取文本,php,regex,regex-lookarounds,Php,Regex,Regex Lookarounds,我需要解析一个自定义模板文件 假设我的模板文件如下所示 @section('section1') some content @endsection @section('section2') some more content @endsection 作为解析的结果,我需要以下结果: array( 'section1' => 'some content', 'section2' => 'some more content' ); 我尝试使用以下代码
@section('section1')
some content
@endsection
@section('section2')
some more content
@endsection
作为解析的结果,我需要以下结果:
array(
'section1' => 'some content',
'section2' => 'some more content'
);
我尝试使用以下代码首先获取节名:
$sectionPattern = '/(?<=\@section\().*?(?=\))/';
preg_match_all($sectionPattern, $this->fileContents, $sections);
foreach($sections[0] as $section) {
$contentPattern = '/(?<=\@section\(' . $section . '\)).*?(?=@endsection)/';
preg_match_all($contentPattern, $this->fileContents, $content);
echo '<pre>';
print_r($content);
}
如果我尝试使用此代码获取每个部分的内容:
$sectionPattern = '/(?<=\@section\().*?(?=\))/';
preg_match_all($sectionPattern, $this->fileContents, $sections);
foreach($sections[0] as $section) {
$contentPattern = '/(?<=\@section\(' . $section . '\)).*?(?=@endsection)/';
preg_match_all($contentPattern, $this->fileContents, $content);
echo '<pre>';
print_r($content);
}
foreach($sections[0]作为$section){
$contentPattern='/(?您可以在一个模式中获取两个匹配项,然后将它们组合起来。您不会将内容显示为多行,但这会处理它。数组映射('trim',$sections[2])
会删除内容两端的空白/换行:
难以置信!我还有很多正则表达式需要学习。谢谢!