简体   繁体   English

PHP在多个自定义标签之间获取文本

[英]PHP get text between multiple custom tags

I need to parse a custom template file. 我需要解析一个自定义模板文件。

Lets say my template file looks like this. 可以说我的模板文件如下所示。

@section('section1')
    some content
@endsection

@section('section2')
    some more content
@endsection

As a result of the parsing i need the following result: 作为解析的结果,我需要以下结果:

array(
    'section1' => 'some content',
    'section2' => 'some more content'
);

I tried to get the section names first with this code: 我尝试首先使用以下代码获取节名称:

$sectionPattern = '/(?<=\@section\().*?(?=\))/';
preg_match_all($sectionPattern, $this->fileContents, $sections);

which works as expected. 它按预期工作。 The result looks like: 结果如下:

$sections = array(
    array(
        0 => 'section1',
        1 => 'section2'
    )
);

If i try to get the content for each section with this code: 如果我尝试使用此代码获取每个部分的内容:

foreach($sections[0] as $section) {
    $contentPattern = '/(?<=\@section\(' . $section . '\)).*?(?=@endsection)/';
    preg_match_all($contentPattern, $this->fileContents, $content);
    echo '<pre>';
    print_r($content);
}

i only get empty arrays and i cant figure out why. 我只得到空数组,我不知道为什么。

Also, if you anyone sees a more elegant way to get the desired result. 此外,如果有人看到一种更优雅的方式来获得所需的结果。 I'm open for suggestions. 我愿意征求意见。

Thanks in advance. 提前致谢。

You can get both matches in one pattern and then combine them. 您可以将两种匹配方式组合在一起,然后将它们组合在一起。 You don't show the content being multi-line but this will handle it. 您不会显示内容是多行的,但是可以处理。 The array_map('trim', $sections[2]) gets rid on the whitespace/newlines at either end of the content: array_map('trim', $sections[2])在内容两端的空白/换行符处摆脱:

preg_match_all("/@section\('([^']+)'\)([^@]+)/", $this->fileContents, $sections);
$sections = array_combine($sections[1], array_map('trim', $sections[2]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM