如果文件名匹配,则排除php包含文件

时间:2015-12-16 13:14:46

标签: php

我在名为 aaa-project.php html/php文件中列出了包含名为 related-portfolio-items.php

<?php include("inc/related-portfolio-aaa.php"); ?>
<?php include("inc/related-portfolio-bbb.php"); ?>
<?php include("inc/related-portfolio-ccc.php"); ?>
<?php include("inc/related-portfolio-bbb.php"); ?>

如果 aaa-project.php 文件中包含这组包含,我需要排除第一个包含“related-portfolio-aaa.php ”。

并在 bbb-project.php 中复制此内容,以排除下一个包含的“ related-portfolio-bbb.php ”include等。 基本上没有相关的投资组合出现在具有该项目的网页上。

所以给每个包含一个Id并在每个项目页面的顶部设置一个if,其中我说明哪个“ related-protfolio-foo.php 被排除在显示或加载之外

2 个答案:

答案 0 :(得分:0)

将此代码复制到新文件中。称之为dependencies.php或其他什么。在开头更改数组以包括每个包含文件。然后,在每个要包含文件的页面上,不要包含整个文件堆栈,只需包含这个文件include "dependencies.php";,该文件只包含不匹配的文件。

// Turn your junk into an array
$includes = array(
    "inc/related-portfolio-aaa.php",
    "inc/related-portfolio-bbb.php",
    "inc/related-portfolio-ccc.php",
    "inc/related-portfolio-bbb.php"
);

// Loop that shit
foreach($includes as $inc){
    $include = true;
    // Check if the current filename is in the format you mentioned
    if(strpos($_SERVER['PHP_SELF'], "-project.php") !== false){
        // Get the prefix of the current filename
        $prefix = explode("-", $_SERVER['PHP_SELF'])[0];
        // Get the suffix of the include
        $suffix = explode(".", explode("-", $inc)[2])[0];
        // Check if it matches
        if($prefix === $suffix) $include = false;
    }
    if($include) include $inc;
}

答案 1 :(得分:0)

您可以使用$_SERVER['PHP_SELF']basename()来实现逻辑。

以下是参考资料:

创建这样的基本模板函数,

function include_files($filename){
    $path_array = array("aaa", "bbb", "ccc");
    $s = explode("-", $filename)[0];
    if (($key = array_search($s, $path_array)) !== false) {
        unset($path_array[$key]);
    }
    foreach($path_array as $str){
        include ("inc/related-portfolio-" . $str . ".php");
    }
}

然后在每个 xxx-project.php 文件中,调用这样的函数,

include_files(basename($_SERVER['PHP_SELF']));

<强>编辑:

让我用一个例子说明这一点。不要在每个文件中包含include_files()函数,而是使用包含此函数的单独文件,并在所有 xxx-project.php 文件中包含 文件,像这样:

<强> include.php

function include_files($filename){
    $path_array = array("aaa", "bbb", "ccc");
    $s = explode("-", $filename)[0];
    if (($key = array_search($s, $path_array)) !== false) {
        unset($path_array[$key]);
    }
    foreach($path_array as $str){
        include ("inc/related-portfolio-" . $str . ".php");
    }
}

在所有 xxx-project.php 文件中包含此 include.php 文件,如下所示:

<强> AAA-project.php

<?php

    include("include.php");

    include_files(basename($_SERVER['PHP_SELF']));

    // rest of your code
?>

<强> BBB-project.php

<?php

    include("include.php");

    include_files(basename($_SERVER['PHP_SELF']));

    // rest of your code
?>

等等。

相关问题