php将[$ id]包含在内($ id。' .php');

时间:2018-04-06 09:22:47

标签: php

我想在其他内容中包含内容,以便拥有嵌套架构。

在我的生活中,我想写下这样的东西:

This is the beginning of my article
[99]
This is the end of my article

因此,我试图获得相当于

的内容
This is the beginning of my article
include(99.php);
This is the end of my article 

怎么做?回调?

1 个答案:

答案 0 :(得分:0)

您可以使用preg_replace_callback()替换模式[99]并替换为include:

$str = 'This is the beginning of my article
[99]
This is the end of my article';

// replace only the pattern "[number]":
$str = preg_replace_callback('~\[(\d+)\]~', function($matches) {
    // define the filename (here a file in the same folder)
    $file = __dir__ . '/' . $matches[1] . '.php';
    // check if exists
    if (!file_exists($file)) return '--not-exists--';
    // include and get as string:
    ob_start();
    include($file);
    $out = ob_get_contents();
    ob_end_clean();
    return $out;

}, $str);

echo $str;

将输出如下内容:

This is the beginning of my article
This is the content of 99.php.
This is the end of my article